text:
Q: Linq to XML get nested child attribute based on parent attribute I need some help with some LINQ to XML. I'm tempted to revert to XPath but am quite keen to learn LINQ to XML properly.
So below is a stripped down version of my XML:
<SData Key="626">
<Event OID="INITIALVISIT">
    <FData FID="MODAL_V10">
        <IGData IOID="MODALITYTABLE">
            <Item OID="I_TABLE_MODAL_DATE_TABLE" Value="2015-06-03" />
            <Item OID="I_TABLE_MODAL_TYPE_TABLE" Value="1" />
        </IGData>
        <IGData IOID="MODALITYTABLE2">
            <Item OID="I_TABLE_MODAL_DATE_TABLE2" Value="2015-06-09" />
            <Item OID="I_TABLE_MODAL_TYPE_TABLE2" Value="1" />
        </IGData>
    </FData>
    <FData FID="UPLOAD_V40">
        <IGData IOID="IG_IMAGE_UNGROUPED">
            <Item OID="I_IMAGE_UPLOAD_XNAT" Value="1" />
            <Item OID="I_IMAGE_UPLOAD_COMPLETE" Value="1" />
        </IGData>
        <IGData IOID="IG_IMAGE_UPLOAD">
            <Item OID="I_IMAGE_UPLOAD_XNAT" Value="1" />
            <Item OID="I_IMAGE_UPLOAD_COMPLETE" Value="1" />
        </IGData>
    </FData>
</Event>
<Event OID="FOLLOWUPVISIT">
...
...
</Event>

What i want to achieve is for every event get the value of Item of attributeOID="I_IMAGE_UPLOAD_COMPLETE". This is what I have so far.
            XNamespace occ = "http://www.cdisc.org/ns/odm/v1.3";
            XNamespace aoc = "http://www.openclinica.org/ns/odm_ext_v130/v3.1";

            var datasubject = data_oc.Descendants(occ + "SData");
            var event = datasubject.Elements(occ + "Event").Attributes("OID");

            foreach (var items in event)
            {
                string EventTypes = items.Value.ToString();
                foreach (var itemData in EventTypes)
                {
                    var Data = from el in datasubject.Descendants(occ + "Event")
                               where (string)el.Attribute("OID=") == itemData
                               select(string)el;
                }
            }

Thank you.

A: var doc=XDocument.Parse(@"your xml");

//Via Linq
var viaLinq=doc.Elements()
  .SelectMany(e => e.Elements())
  .SelectMany(e => e.Elements())
  .SelectMany(e => e.Elements())
  .SelectMany(e => e.Elements())
  .Where(w => w.Attribute("OID").Value=="I_IMAGE_UPLOAD_XNAT")
  .Select(e => e.Attribute("Value").Value);

//Even better use Xpath. It makes all this very simple
var viaXPath=doc.XPathSelectElements("//Item[@OID='I_IMAGE_UPLOAD_XNAT']")
  .Select(e => e.Attribute("Value").Value);

A: Try this, not sure how it works good in terms of performance.
 XDocument po = XDocument.Load("XMLFile1.xml");
        // LINQ to XML query
        var list1 = po.Descendants("Event")
                        .Select(x =>
                            x.Descendants("Item").Where(t =>
                                (string)t.Attribute("OID") == "I_IMAGE_UPLOAD_COMPLETE").Select(m =>
                                    new { Event = x, AttributeValue = m.Attribute("Value") })
                                ).Where(f => f.FirstOrDefault() != null).ToList();


text:
Q: Shell Script improvement for getting diff result I have shell Script written which does a job of comparing two files and and gives me result in a HTML format for defects. But i want to improve it so that i can only get modified files defects instead of legacy defects also. I am using this script to get Coverity report.
 while read line; do
n=$((++n))
if echo $line | grep '^[[:space:]]*>' &>/dev/null; then
    if [ $(($n % 2)) -eq 1 ]; then
        # TODO somehow get proper defect number from html
        # echo "Defect num: $(($n/2 + 1))"
        def_num=$((++def_num))
    fi
    echo $line | sed -n -e 's/>[[:space:]]*\(.*\)/\1/p'
    if [ $(($n % 2)) -eq 0 ]; then
        echo "-------------------------------"
    fi

done < <(diff -y -W 200 ./cov-results-base/result.filt ./cov-results-changed/result.filt)

echo "==============================="
echo

echo "Number of defects in old code: $(tac cov-results-base/summary.xml |
                    sed -n '/num/{s|<num>\(.*\)</num>|\1|p; q;}')"
echo "Number of defects in new code: $(tac cov-results-changed/summary.xml |
                    sed -n '/num/{s|<num>\(.*\)</num>|\1|p; q;}')"

A: This enables you to get the last modification time of a file and the compare with the current time.
now=`date +%s`
modified=`stat -c "%Y" $file`

if [ $(($now-$modified)) -gt 0 ]; then
     echo "not modified";
else
     echo "modified";
fi

I hope that this is what you wanted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS Development: Get private IP and port from NSReadStream I am developing an app for iOS. In my app there is a working TCP-connection to a server, realized via NSStreams. Now I need the port the connection is using which generates some problems.
I can get the IP from iterating through the interfaces of the device but for the portnumber I have to get the information from the socket. In the following code I try to get the socket from my working and open NSInputStream _readstream. The problem is, that CFSocketCopyAddress is nil and I cannot see why. Can somebody else?
Any help is very much appreciated!
// Initializing some variables we need
CFSocketContext context;
memset(&context, 0, sizeof(context));
context.info = (__bridge void*)self;
NSString *property = @"kCFStreamPropertySocketNativeHandle";

// Get hands on the used socket via the socket native handle
CFSocketNativeHandle *socketNativeHandle = (CFSocketNativeHandle*)CFReadStreamCopyProperty((__bridge CFReadStreamRef)(_readStream), (__bridge CFStringRef)(property));
CFSocketRef cfSocket = CFSocketCreateWithNative(NULL, *socketNativeHandle, kCFSocketNoCallBack, nil, &context);

// Ask the socket for the address information
CFDataRef               dataRef = CFSocketCopyAddress(cfSocket);                        // dataRef is always nil :(
struct sockaddr_in      *sockaddr = (struct sockaddr_in*)CFDataGetBytePtr(dataRef);

int portnumber = sockaddr->sin_port;

A: OKay, this works for me now. Maybe I can help someone coming from google or from somewhere else....
- (NSNumber*) getPortnumber{
    int             port        = -1;

    CFSocketContext context;
    memset(&context, 0, sizeof(context));
    context.info = (__bridge void*)self;

    // Get Socket native handle from existing stream
    CFDataRef socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)(_writeStream), kCFStreamPropertySocketNativeHandle);

    // Get the native handle
    CFSocketNativeHandle handle;
    CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), &handle);

    // Get the socket
    CFSocketRef cfSocket = CFSocketCreateWithNative(NULL, handle, kCFSocketNoCallBack, nil, &context);

    // CFSocketCopyAddress will return the address of the socket
    CFDataRef               dataRef = CFSocketCopyAddress(cfSocket);
    struct sockaddr_in      *sockaddr = (struct sockaddr_in*)CFDataGetBytePtr(dataRef);

    // Get the port from the address information
    port = sockaddr->sin_port;

    // Output Objective-C friendly =)
    NSNumber *portnr = [NSNumber numberWithInt:port];
    return portnr;
}


text:
Q: Passing variable amount to Paypal donation button not working I have tried to pass a derived total to paypal donation button (non-hosted button), but Paypal is still showing 0. I tried everything I read on this site, but still couldn't make it work. Any help is appreciated.
Here is the script I have.
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31
      && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function sum() {
    var txtPKDValue = document.getElementById('txtPKD').value;
    var txtHeartValue = document.getElementById('txtHeart').value;
    var txtAlzheimerValue = document.getElementById('txtAlzheimer').value;
    var txtDiabetesValue = document.getElementById('txtDiabetes').value;
    var txtStridesValue = document.getElementById('txtStrides').value;
    var txtNightWalkValue = document.getElementById('txtNightWalk').value;
    var txtJingleValue = document.getElementById('txtJingle').value;
    var txtMSValue = document.getElementById('txtMS').value;
    var txtDimesValue = document.getElementById('txtDimes').value;
    var txtStepsValue = document.getElementById('txtSteps').value;
    var txtUnspecifiedValue = document.getElementById('txtUnspecified').value;

    if (txtPKDValue == "")
        txtPKDValue = 0;
    if (txtHeartValue == "")
        txtHeartValue = 0;
    if (txtAlzheimerValue == "")
        txtAlzheimerValue = 0;
    if (txtDiabetesValue == "")
        txtDiabetesValue = 0;
    if (txtStridesValue == "")
        txtStridesValue = 0;
    if (txtNightWalkValue == "")
        txtNightWalkValue = 0;
    if (txtJingleValue == "")
        txtJingleValue = 0;
    if (txtMSValue == "")
        txtMSValue = 0;
    if (txtDimesValue == "")
        txtDimesValue = 0;
    if (txtStepsValue == "")
        txtStepsValue = 0;
    if (txtUnspecifiedValue == "")
        txtUnspecifiedValue = 0;

    var result = parseInt(txtPKDValue) + parseInt(txtHeartValue) + parseInt(txtAlzheimerValue) +
        parseInt(txtDiabetesValue) + parseInt(txtStridesValue) + parseInt(txtNightWalkValue) + parseInt(txtJingleValue) + parseInt(txtMSValue) + parseInt(txtDimesValue)
        + parseInt(txtStepsValue) + parseInt(txtUnspecifiedValue);
    if (!isNaN(result)) {
        document.getElementById('txtTotal').value = result;
    }
}

      <fieldset>
        <legend>Donations</legend>

            Name
            :

              <input id="txtName" type="text" />

            E-Mail
            :

              <input id="txtMail" type="text" />

                Sacramento Walk for PKD *

            :

              <input id="txtPKD"  type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Heart Walk *

            :

              <input id="txtHeart" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Walk to End Alzheimer's *

            :

              <input id="txtAlzheimer" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Walk to Cure Diabetes *

            :

              <input id="txtDiabetes" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Making Strides of Sacramento *

            :

              <input id="txtStrides" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Light the Night Walk *

            :

              <input id="txtNightWalk" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Jingle Bell Run/Walk *

            :

              <input id="txtJingle" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Walk MS *

            :

              <input id="txtMS" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                March of Dimes *

            :

              <input id="txtDimes" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                  Take Steps

            :

              <input id="txtSteps" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

              Unspecified
            :

              <input id="txtUnspecified" type="text" onkeyup="sum()" onkeypress="return isNumberKey(event)" />

                Total Amount

            :

              <input id="txtTotal" type="text" readonly="true" onkeypress="return isNumberKey(event)" />

                Comments *

            :

              <textarea rows="5" id="txtComment" cols="20"></textarea>

      <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
        <input type="hidden" name="cmd" value="_donations">
        <input type="hidden" name="business" value="XXXXXXXXXXXXX">
        <input type="hidden" name="lc" value="US">
        <input type="hidden" name="item_name" value="GFF">
        <input type="hidden" name="item_number" value="GFF2015">
        <input type="hidden" name="no_note" value="0">
        <input type="hidden" name="cn" value="Add special instructions to the seller:">
        <input type="hidden" name="no_shipping" value="1">
        <input type="hidden" name="currency_code" value="USD">
        <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">
        <input type="hidden" name="amount" id="txtTotal" >
        <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

      </form>

      </fieldset>

A: You have two different elements with id=txtTotal. IDs must be unique. Any code setting txtTotal's value will only set the first one that's found - the readonly version here:

  <input id="txtTotal" type="text" readonly="true" onkeypress="return isNumberKey(event)" />

Eliminate that row and you should be in better shape. Or give it a new ID, and set both at the same time:
if (!isNaN(result)) {
  document.getElementById('txtTotal').value = result;
  document.getElementById('displayTxtTotal').value = result;
}


text:
Q: How to let struct hold a thread and destroy thread as soon as it go out of scope struct ThreadHolder{
  state: ???
  thread: ???
}

impl ThreadHolder {
  fn launch(&mut self) {
    self.thread = ???
    // in thread change self.state
  }
}

#[test]
fn test() {
  let mut th = ThreadHolder{...};
  th.launch();
  // thread will be destroy as soon as th go out of scope
}

I think there is something to deal with lifetime, but I don't know how to write it.

A: What you want is so simple that you don't even need it to be mutable in any way, and then it becomes trivial to share it across threads, unless you want to reset it. You said you need to leave a thread, for one reason or another, therefore I'll assume that you don't care about this.
You instead can poll it every tick (most games run in ticks so I don't think there will be any issue implementing that).
I will provide example that uses sleep, so it's not most accurate thing, it is painfully obvious on the last subsecond duration, but I am not trying to do your work for you anyway, there's enough resources on internet that can help you deal with it.
Here it goes:
use std::{
    sync::Arc,
    thread::{self, Result},
    time::{Duration, Instant},
};

struct Timer {
    end: Instant,
}

impl Timer {
    fn new(duration: Duration) -> Self {
        // this code is valid for now, but might break in the future
        // future so distant, that you really don't need to care unless
        // you let your players draw for eternity
        let end = Instant::now().checked_add(duration).unwrap();

        Timer { end }
    }

    fn left(&self) -> Duration {
        self.end.saturating_duration_since(Instant::now())
    }

    // more usable than above with fractional value being accounted for
    fn secs_left(&self) -> u64 {
        let span = self.left();

        span.as_secs() + if span.subsec_millis() > 0 { 1 } else { 0 }
    }
}

fn main() -> Result<()> {
    let timer = Timer::new(Duration::from_secs(10));
    let timer_main = Arc::new(timer);

    let timer = timer_main.clone();
    let t = thread::spawn(move || loop {
        let seconds_left = timer.secs_left();
        println!("[Worker] Seconds left: {}", seconds_left);

        if seconds_left == 0 {
            break;
        }

        thread::sleep(Duration::from_secs(1));
    });

    loop {
        let seconds_left = timer_main.secs_left();
        println!("[Main] Seconds left: {}", seconds_left);

        if seconds_left == 5 {
            println!("[Main] 5 seconds left, waiting for worker thread to finish work.");
            break;
        }

        thread::sleep(Duration::from_secs(1));
    }

    t.join()?;

    println!("[Main] worker thread finished work, shutting down!");

    Ok(())
}

By the way, this kind of implementation wouldn't be any different in any other language, so please don't blame Rust for it. It's not the easiest language, but it provides more than enough tools to build anything you want from scratch as long as you put effort into it.
Goodluck :)

A: I think I got it work
use std::sync::{Arc, Mutex};
use std::thread::{sleep, spawn, JoinHandle};
use std::time::Duration;

struct Timer {
    pub(crate) time: Arc<Mutex<u32>>,
    jh_ticker: Option<JoinHandle<()>>,
}

impl Timer {
    fn new<T>(i: T, duration: Duration) -> Self
    where
        T: Iterator<Item = u32> + Send + 'static,
    {
        let time = Arc::new(Mutex::new(0));

        let arc_time = time.clone();
        let jh_ticker = Some(spawn(move || {
            for item in i {
                let mut mg = arc_time.lock().unwrap();
                *mg = item;
                drop(mg); // needed, otherwise this thread will always hold lock
                sleep(duration);
            }
        }));

        Timer { time, jh_ticker }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        self.jh_ticker.take().unwrap().join();
    }
}

#[test]
fn test_timer() {
    let t = Timer::new(0..=10, Duration::from_secs(1));
    let a = t.time.clone();
    for _ in 0..100 {
        let b = *a.lock().unwrap();
        println!("{}", b);
        sleep(Duration::from_millis(100));
    }
}


text:
Q: PHP - Simple Subtraction Doesn't Add Up I have no idea why this simple mathematical equation doesn't work. It's making me crazy - am I blind? Instead of subtracting $number from $Amount2 it produces a negative number. So if $Amount2 starts with a value of 100 and $number is a value of 10 I get -10 instead of 90 as the result.
//find how much green they are holding
 $resultto = db_query("SELECT * FROM Users_Panickles WHERE PSID ='$PSID'");
$rowgifter = db_fetch_array($resultgifter);//fetch the name of the giftee character
$Amount2 = $resultgifter["Amount"];

//now alter the accounts
$Amount2 = $Amount2 - $number; //subtract the gift from the gifter's account and update the record
db_query ("UPDATE Users_Panickles SET Amount='$Amount2' WHERE PSID = '$PSID'");


text:
Q: How to pass the value in SQL Server selected columns Sorry it is my 1st to use stack overflow and I have a datagridview and only 3 columns I loaded from SQL Server:
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 1000
    [employeesID], [firstName], [lastName], [middleName],
    [phoneNumber], [passCode], [EditDate], [DOB], [image]
FROM
    [PointofSale].[dbo].[employees]

I concat the firstName and lastName and I want to pass the value from SQL Server to a textbox. I don't know the logic.
public void datagridinsert()
{
    string constring = ConfigurationManager.ConnectionStrings["PointofSale.Properties.Settings.PointofSaleConnectionString"].ConnectionString; using (var con = new SqlConnection(constring))
    {
        con.Open(); using (var command = new SqlCommand("SELECT employeesID, CONCAT(lastName, ' ', firstName, ' ', middleName) AS Name, createDate, designation FROM employees", con))
        {
           SqlDataReader read = command.ExecuteReader();

           while (read.Read())
           {
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[0].Value = read["employeesID"].ToString();
                dataGridView1.Rows[n].Cells[1].Value = read["Name"].ToString();
                dataGridView1.Rows[n].Cells[2].Value = read["createDate"].ToString();
                dataGridView1.Rows[n].Cells[3].Value = read["designation"].ToString();
            }
        }
    }
}


text:
Q: Partial string match in jsonb using Hasura graphql API? I'm trying to do the following query:
query Feeds($id: Int!) {
  feed_by_pk(id: $id) {
    feed_items(where: {contents: {_contains: {blocks: [{text: "%test%"}]}}}) {
      id
      contents
      created_at
      created_by
      last_edited
      user {
        id
        name
      }
    }
  }
}

Where I'd like to match the value 'text' against 'test' but ignoring case (so Test, tESt, etc will hit) and also partial matching (i.e. "this is a Test" will work).
I've tried using %test% to no avail, is there a specific way to do this for JSONBs with Hasura?


text:
Q: Android simple calculator crash I am new to android developing and made a simple calculator project. However, my app keeps crashing and I have no idea why
Java Codes:
package com.example.zhiwen.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Button plus,minus,times,divide;
TextView textview3;
EditText first, second;
double no1 = 0, no2 = 0;
double answer = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    plus = (Button) findViewById(R.id.plus);
    minus = (Button) findViewById(R.id.minus);
    times = (Button) findViewById(R.id.times);
    divide = (Button) findViewById(R.id.divide);
    textview3 = (TextView) findViewById(R.id.textview3);
    first = (EditText) findViewById(R.id.editText);
    second = (EditText) findViewById(R.id.editText2);
}

public void ClickMeButton(View view){
    no1 = Integer.parseInt(first.toString());
    no2 = Integer.parseInt(second.toString());
    answer = no1 + no2;
    textview3.setText("Answer: " + answer);
}
public void ClickMeButton2(View view) {
    no1 = Integer.parseInt(first.toString());
    no2 = Integer.parseInt(second.toString());
    answer = no1 - no2;
    textview3.setText("Answer: " + answer);
}
public void ClickMeButton3(View view) {
    no1 = Integer.parseInt(first.toString());
    no2 = Integer.parseInt(second.toString());
    answer = no1 * no2;
    textview3.setText("Answer: " + answer);
}
public void ClickMeButton4(View view) {
    no1 = Integer.parseInt(first.toString());
    no2 = Integer.parseInt(second.toString());
    answer = no1 / no2;
    textview3.setText("Answer: " + answer);
}}

Stack Trace:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zhiwen.calculator, PID: 2027
java.lang.IllegalStateException: Could not execute method for
android:onClick
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:6207)
at android.widget.TextView.performClick(TextView.java:11094)
at android.view.View$PerformClick.run(View.java:23639)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6207)
at android.widget.TextView.performClick(TextView.java:11094)
at android.view.View$PerformClick.run(View.java:23639)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NumberFormatException: For input string:
"android.support.v7.widget.AppCompatEditText{271441f VFED..CL.
........ 0,57-441,193 #7f0b0063 app:id/editText}"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at
com.example.zhiwen.calculator.MainActivity.ClickMeButton(MainActivity.java:33)
at java.lang.reflect.Method.invoke(Native Method)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6207)
at android.widget.TextView.performClick(TextView.java:11094)
at android.view.View$PerformClick.run(View.java:23639)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

A: You want to change
no1 = Integer.parseInt(first.toString());

to
no1 = Integer.parseInt(first.getText ().toString());

same for second

A: you are getting the value from editText in wrong way
    no1 = Integer.parseInt(first.toString());
    no2 = Integer.parseInt(second.toString());
    answer = no1 + no2;
    textview3.setText("Answer: " + answer);
it should be first.getText().toString();


text:
Q: Technical - What does the iPhone use to send Device Motion Updates I'm not having problem with the CODE, I want to know what does the iPhone use for CoreMotions (because I'd like to repair it / get it repaired).
I'm not sure if this should be posted here or not.
I would like to know what does the iPhone use to send motion updates. And what does it use to process them.
My problem is, there's some problem with my iPhone, since it's not sending motion updates. I wrote a small project, to test what I'm receiving. On a working device I got output like this:
2013-11-15 09:39:44.415 GyroTest[12165:60b] QuaternionX -0.508156 QuaternionY -0.515390 QuaternionZ 0.487396 QuaternionW 0.488463
    UserAccelX 0.002124 UserAccelY 0.007351 UserAccelZ 0.006973
    RotationRateX -0.051634 RotationRateY 0.080035 RotationRateZ 0.025516
    MagneticFieldX 0.000000 MagneticFieldY 0.000000 MagneticFieldZ 0.000000 MagneticFieldAccuracy -1 @ 386510.678629
2013-11-15 09:39:44.418 GyroTest[12165:60b] -1.395383
2013-11-15 09:39:44.419 GyroTest[12165:60b] -1.522387
2013-11-15 09:39:44.420 GyroTest[12165:60b] -2.972348

But on my device (the faulty one) I get:
2013-11-15 09:39:18.191 GyroTest[12165:60b] (null)
2013-11-15 09:39:18.192 GyroTest[12165:60b] 0.000000
2013-11-15 09:39:18.193 GyroTest[12165:60b] 0.000000
2013-11-15 09:39:18.194 GyroTest[12165:60b] 0.000000

Here's my sample project:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.motionManager = [[CMMotionManager alloc] init];
    self.referenceAttitude = nil;
    [self enableGyro];
    for (int i = 0 ; i < 100 ; ++i) {
        [self getDeviceGLRotationMatrix];
    }
}

-(void) enableGyro{
    CMDeviceMotion *deviceMotion = self.motionManager.deviceMotion;
    CMAttitude *attitude = deviceMotion.attitude;
    self.referenceAttitude = attitude;
    [self.motionManager startGyroUpdates];
    [self.motionManager startAccelerometerUpdates];
    [self.motionManager startDeviceMotionUpdates];
    [self.motionManager startMagnetometerUpdates];
}

-(void) getDeviceGLRotationMatrix
{
    CMDeviceMotion *deviceMotion = self.motionManager.deviceMotion;
    CMAttitude *attitude = deviceMotion.attitude;

    if (self.referenceAttitude != nil)
        [attitude multiplyByInverseOfAttitude:self.referenceAttitude];
    NSLog(@"------------------");
    NSLog(@"%@",self.motionManager.deviceMotion);
    NSLog(@"%f",attitude.yaw);
    NSLog(@"%f",attitude.pitch);
    NSLog(@"%f",attitude.roll);
    sleep(1);
}

A: #include <CoreMotion/CoreMotion.h>
#import "ViewController.h"

@interface ViewController () {

}

@property (strong, nonatomic) CMMotionManager * motionManager;
@property (strong, nonatomic) NSOperationQueue * queue;

- (void) startMotionDetection;
- (void) doSomeThingWithTheMotionValues: (NSDictionary *) motionValues;

@end

@implementation ViewController
@synthesize motionManager = _motionManager;
@synthesize queue = _queue;

- (void)viewDidLoad {
     [super viewDidLoad];
     if (!_motionManager) _motionManager = [[CMMotionManager alloc] init];
     if (!_queue) _queue = [[NSOperationQueue alloc] init];

     [self startMotionDetection];
}

- (void) startMotionDetection {
     // Setting up the handler first.
     CMDeviceMotionHandler dmHandler = ^(CMDeviceMotion * aMotion, NSError * error) {
     CMDeviceMotion *deviceMotion = self.motionManager.deviceMotion;
     CMAttitude * anAttitude = deviceMotion.attitude;
     CMQuaternion quaternion = anAttitude.quaternion;
     NSNumber * yaw = [NSNumber numberWithFloat:anAttitude.yaw*kRadiansToDegrees];
     NSNumber * roll = [NSNumber numberWithFloat:anAttitude.roll*kRadiansToDegrees];
     NSNumber * pitch = [NSNumber numberWithFloat:anAttitude.pitch*kRadiansToDegrees];

     NSNumber * x = [NSNumber numberWithFloat:quaternion.x];
     NSNumber * y = [NSNumber numberWithFloat:quaternion.y];
     NSNumber * z = [NSNumber numberWithFloat:quaternion.z];
     NSNumber * w = [NSNumber numberWithFloat:quaternion.w];

     // Creating the NSDictionary to hold the key/value pairs with the NSNumber objects
     NSDictionary * sensorValues = [NSDictionary dictionaryWithObjectsAndKeys:
                                                           yaw,      @"Yaw",
                                                           roll,     @"Roll",
                                                           pitch,    @"Pitch",
                                                           x,      @"x",
                                                           y,     @"y",
                                                           z,    @"z",
                                                           w,    @"w",
                                                           nil];

     // Sending the dictionary to the processing method
     [self performSelectorOnMainThread: @selector(doSomeThingWithTheMotionValues:)
                                                   withObject: sensorValues
                                                waitUntilDone: YES];
     // Checking if some errors occured
     if (error) {
           NSLog(@"Could not start/continue Device Motion Updates with error:\n%@",error);
           // Restart the motion manager in case of error
           [self.motionManager stopDeviceMotionUpdates];
           [self setMotionManager:nil];
           [self setQueue:nil];
           if (!_motionManager) _motionManager = [[CMMotionManager alloc] init];
           if (!_queue) _queue = [[NSOperationQueue alloc] init];
           [self startMotionDetection];
           return;
      }
    }; // End of handler block

      if (self.motionManager.deviceMotionAvailable) {
           self.motionManager.deviceMotionUpdateInterval = kMotionUpdateInterval;
           [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical
                                                                                toQueue:self.queue
                                                                                withHandler:dmHandler];
      } else {
           ALERT(nil, @"Motion sensors not available");
      }
}

- (void) doSomeThingWithTheMotionValues: (NSDictionary *) motionValues {
      UIInterfaceOrientation orient = [CommonSessionData currentOrientation];
      float value = -1000.0;

      NSNumber * roll = (NSNumber *)[motionValues valueForKey:@"Roll"];
      float attitudeRoll = roll.floatValue;
      NSNumber * x = (NSNumber *)[motionValues valueForKey:@"x"];
      NSNumber * y = (NSNumber *)[motionValues valueForKey:@"y"];
      NSNumber * z = (NSNumber *)[motionValues valueForKey:@"z"];
      NSNumber * w = (NSNumber *)[motionValues valueForKey:@"w"];
      double quaternionPitch = pitch(x.doubleValue, y.doubleValue, z.doubleValue, w.doubleValue)*kRadiansToDegrees;

      value = UIInterfaceOrientationIsPortrait(orient) ? quaternionPitch : (orient == UIInterfaceOrientationLandscapeLeft ? attitudeRoll : -attitudeRoll);
}

And helper methods :
double pitch(double x, double y, double z, double w) {
    return atan2(2*(y*z + w*x), w*w - x*x - y*y + z*z);
}

double yaw(double x, double y, double z, double w) {
    return asin(-2*(x*z - w*y));
}

double roll(double x, double y, double z, double w) {
    return atan2(2*(x*y + w*z), w*w + x*x - y*y - z*z);
}


text:
Q: Conditionally adding Items to the Excel ListBox control I have Excel data like in the sample shown below and 3 ListBoxes
Example of my spreadsheet:
 A          B         C
1423    21-03-16    John
2987    03-03-16    Steve

My issue: In my ListBox2 I would like to only show what is in the A columns only if 14 days have passed the days in column B.
I have this code, but cant get it working
     Dim rngToSearch As Range
    Dim rngToFind As Range
    Dim valToFind As Variant
    Dim arrClearList()

    valToFind = TextBox1.Value
   With Worksheets("Data2")
        Set rngToSearch = .Columns("A")
    End With
    Set rngToFind = rngToSearch.Find(What:=valToFind, _
            LookIn:=xlFormulas, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, _
            MatchCase:=False)

    If Not rngToFind Is Nothing Then

       Call ClearList(Me.ListBox1)
   ListBox1.AddItem

        With ListBox1
            .List(.ListCount - 1, 0) = rngToFind.Value
            .List(.ListCount - 1, 1) = rngToFind.Offset(0, 1).Value
            .List(.ListCount - 1, 2) = rngToFind.Offset(0, 3).Value
            .List(.ListCount - 1, 3) = rngToFind.Offset(0, 4).Value
            .List(.ListCount - 1, 4) = rngToFind.Offset(0, 5).Value

        End With

A: Pertinent to you question in regards to conditionally populating the ListBox2: your code snippet does not implement that part. You can add Items from Column "A" based on the DateTime value in the column "B" as shown in the following VBA code snippet using DateDiff function to check the condition you have specified (14 days pass since the date value in Column "B"):
Sub AddItemsToListbox2()
Dim I As Integer
Dim maxRow As Integer

maxRow = 100
ListBox2.Clear
For I = 1 To maxRow
    If (DateDiff("d", Now, Range("B" & I).Value) > 14) Then
        ListBox2.AddItem Range("A" & I)
    End If
Next I
End Sub

The solution was tested on sample data set shown below (the last item was added to the ListBox2):
A       B           C
1423    3/21/2016   John
2987    3/3/2016    Steve
3345    4/28/2016   Anna

Hope this may help.


text:
Q: Cannot invoke sendData I am getting the error below while attempting to send the current time of a song however I get this error, but it says that the first argument is supposed to be of type NSObject I am pretty sure
Cannot invoke sendData with an argument list of type '(NSTimeInterval!, toPeers: [AnyObject]!, withMode: MCSessionSendDataMode)'

func hostPhoneTime(){
    //songTime is of type NSTimeInterval!
    appDelegate.mpcHandler.session.sendData(songTime_, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Unreliable)

}

A: in Apple docs says it is a NSData, check it out
Edit:
Here's an example of how you can transform a value like a NSIntervalTime (which is a Double) to a NSData
var time: NSTimeInterval = 112
// it's easier to parse your data to a String first
var timeString = "\(time)"
// then this is how you get a NSData
let timeData = timeString.dataUsingEncoding(NSUTF8StringEncoding)!

// Let's imagine here you send your NSData to another place like a socket or something that receives NSData

// Your transform it back to a string
var receivedTimeString = NSString(data: timeData, encoding: NSUTF8StringEncoding)!
// And finally to your desired type
var receivedTime: NSTimeInterval = NSTimeInterval(Double(receivedTimeString as String)!)


text:
Q: Why do material-ui modules show in both node_modules and src after Webpack 4 tree shaking? The Cloud Native Interactive Landscape is an open-source, browser-only application that loads a static React app for visualizing the cloud native ecosystem:

*

*Try the app

*View source
You can interactively view the results of webpack-bundle-analyzer and here is a snapshot:

I don't understand why @material-ui/core/es appears in both node_modules and src. More generally, I'm trying to understand if our tree-shaking is optimally implemented, or if there's a better way to configure it. I would also appreciate hearing if we're optimally tree-shaking lodash. (Note that we're only targeting evergreen browsers.)
Please feel free to fork the repo and edit webpack.config.prod.js. If you open a pull request, Netlify will build and deploy a test server and you can check for results under test-server-url/report.html.

A: So let me preface that the es name was poorly chosen. src would be much more fitting since it's just that: The untranspiled source code. This is documented in the docs under minimizing bundlesize
With webpack 4 and proper module entries in the respective package.json you should automatically pull in the esmodule version of those packages. The esmodule version is responsible for most of the tree-shaking optimization in webpack.
@material-ui/core already has a proper entry. This is however only at the top level an esmodule version. The actual components are then written with commonJS which does not allow tree-shaking in webpack. We have an open PR but we might wait for the next major since we don't test on the compiled files which makes changes to the build scary.
As to why this appears as a concatenated module I can't help you with that. While investigating I made the same observation (https://github.com/eps1lon/material-ui-treeshaking). It is probably an issue with the bundle-analyzer and has no actual impact on the generated chunks (e.g. https://github.com/webpack-contrib/webpack-bundle-analyzer/issues/188).
Overall I would recommend not using the es version and simply letting webpack target the module entry. It allows tree shaking for the bulk of the package but you loose out on some micro-optimization. I tested transpiling everything to esmodules and made some improvements to the stat size of a bundle from 200KB to 180KB but hit some gzip deoptimization which increased the gzipped size by 1KB (meme version). So don't stress about tree-shaking for every tiny file.


text:
Q: Converting C++ class to procedural API: common way of replacing member variables? I'm converting a C++ class, let's call it render, which only ever had one instance used (singleton-but-not-offically), to a purely procedural style for use in a C program. Which being what it is, a simple software renderer, probably should have been written as such in the first place.
The ex-class mostly just dealt with a ton of generically-named private variables, everything from lone bytes to large arrays of binary data. unsigned char frame_counter, char* frame_data, unsigned char palette[256][128][3], etc. which is what I'm trying to replace.
I'm renaming my functions in a simple way, like: render::load_sprite(const char* file) -> render_load_sprite(const char* file)
Global "member" variables:

*

*Generally considered bad / to be avoided. Possible conflicts at some point.

*Don't know how I should rename members. Maybe prefix like renderer_palette? Kinda verbose from the inside.

*What if I want some variables to modifiable without wrapper function?

State struct:

*

*OOP-like, but I'm dealing with what should a singular, static API.

*Has to be passed around everywhere. Kinda verbose from the outside.

*Has to be initialized.
Is the preferred choice in this instance globals, struct, or is there another option?

A: Eeek.. Globals? Shoot yourself. Never use globals. Big no no. Ruins reentrancy and kills your code.
All C code I write looks like this:
struct object {
    int data;
};

void object_init(struct object *self);
void object_update(struct object *self, float dt);
int object_write_to_file(struct object *self, const char *file);

*

*for anything that is not trivial like radians(float degrees) use a struct and pass it as first argument called self everywhere (do not use this even if allowed in C because you will have problems mixing with C++)

*keep file name and struct name the same

*prefix all methods that operate on the struct with struct name

*do not use typedef struct ... it makes glancing over code harder

*always keep all data in structs that stem from a root application object. ie struct application { struct object obj; ... }. This allows you to easily make as many instances of the application as you like (provided that all libraries you use also are designed as OOP objects without static state). Regardless, it is a good practice for your code.

*Doing this allows you to have full control over: reentrancy, data locality, data ownership, data modification, code readability. Generally you get much better quality too and can easily make your app multithreaded because without global state everything that needs to be locked is inside the same struct.

*Over time you start to appreciate verbosity a lot because EVERYTHING you do with your code becomes easier and you can understand what the code does just by looking at it. You know that self->member is a reference to a variable that is passed to current method. You know this variable is local to the object. You know self is the object you are currently operating on. You know that any access to members of self probably has to be locked by a lock called self->lock if mutual exclusion is necessary. Easy inferences like these really speed up development time and make your life easier.


text:
Q: Salesforce Code Deployment : ANT & Changesets learning via developer edition I am trying to learn salesforce code deployment process.
I believe deploying code via ANT & Changesets are the most common ways to deploy your changes into Production.
I would like to get a hands-on (self-learning) with these tools as such is it possible to learn about these tools with my developer edition itself ?

A: You can try self learning with two sample developer orgs .Try moving some metadata and code from one developer to another developer org .
There is a small video that can help you on how to achieve this
https://www.youtube.com/watch?v=f5UlWurQzHQ
The installation steps are documented below
http://www.salesforce.com/us/developer/docs/daas/Content/forcemigrationtool_install.htm
The documentation on how to use this is as below
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_deploying_ant.htm

A: You can use developer edition very well to get hands-on on Salesforce Deployment experience.
Here are some quick links :

*

*Changeset Video , Change set overview and Best practices

*Using Eclipse for Metadata Migration

*Basics of ANT Migration tool
Some advance reference materials :

*Automated backup of Salesforce Org using ANT

*Using Jenkins for Continuous integration


text:
Q: Cannot stop button click event when i click in another button When i click in "A+" more times than possible to change and then i click on "A-", the font-size increases instead of decreasing in first click.
How can i stop this event during click in another button?

$(document).ready(function(){
  var fontSize = 16;
  /* Increase Text */
  $("#increase-text").click(function(){
    if(fontSize >= 24) {
      return false;
   }else {
    $(".main-content").css("font-size", fontSize + "px");
     fontSize = fontSize + 1;
     console.log('+ ' + fontSize);
    }

  });

  /* Decrease Text */
  $("#decrease-text").click(function(){

    if(fontSize <= 10) {
   return false;
    }else {

   $(".main-content").css("font-size", fontSize + "px");
   fontSize = fontSize - 1;
   console.log('+ ' + fontSize);
   }
  });
  /* Default */
  $("#normal-text").click(function(){
    var fontSize = 16;
    $(".main-content").css("font-size", fontSize + "px");
    $('body').removeClass("contrast-white");
    $('body').removeClass("contrast-black");
  });
  /* Contrast Black */
  $("#contrast-b").click(function(){
    $('body').addClass("contrast-black");
    $('body').removeClass("contrast-white");
  });

  /* Contrast White */
  $("#contrast-w").click(function(){
     $('body').addClass("contrast-white");
     $('body').removeClass("contrast-black");
  });
});
.controllSize a {
    -webkit-transition: 0.5s ease-in-out;
    -moz-transition: 0.5s ease-in-out;
    -ms-transition: 0.5s ease-in-out;
    -o-transition: 0.5s ease-in-out;
    transition: 0.5s ease-in-out
}
.controllSize {
    text-align: right
}
.controllSize .boxCtrl {
    display: inline-block
}
.controllSize a {
    width: 32px;
    height: 32px;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    background-color: #f4f4f4;
    border: 2px solid #fff;
    color: rgba(0, 0, 0, 0.9);
    text-decoration: none;
    font-size: 14px
}
.controllSize a:hover {
    background-color: #c8c8c8;
    border-color: #000
}
.controllSize a#contrast-b {
    background-color: #000;
    color: #fff;
    font-weight: bold;
}
.controllSize a#contrast-w {
    background-color: #f4f4f4;
    color: #000;
    font-weight: bold;
}

/* Constrast White */
html body.contrast-white {
    background-color: #fff !important;
    color: #000 !important;
    box-shadow: none;
}

/* Constrast Black */
html body.contrast-black {
    background-color: #000 !important;
    color: #fff !important;
    box-shadow: none;
}

  A-
  A+
  A
  A
  A

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan porta nisl id ullamcorper. Pellentesque lobortis, neque ac suscipit feugiat, justo eros egestas magna, ut euismod dolor orci vel turpis. Maecenas in odio non justo consequat luctus quis quis elit. Integer ultrices lorem sit amet libero luctus, ac aliquam augue scelerisque. Sed ultrices aliquet metus id aliquam. Duis elementum turpis ut eros rutrum, vel venenatis leo venenatis. Phasellus condimentum viverra massa, quis dignissim sem accumsan dictum. Nullam vulputate dolor eget sollicitudin tincidunt.

A: You should change the order of your operations - first change the font size and then change the css -
fontSize = fontSize + 1;
$(".main-content").css("font-size", fontSize + "px");

also in the decrease text function.
I would also change the normal-text to not redeclare the fontSize variable
fontSize = 16;


text:
Q: Updating Constraints in UITableViewCell are not properly I want to make a dynamic cell in my UITableView in case of image height. Everything works properly, but when I scroll my UITableView, debugger is yelling me about bad constraints in my cell, but cells look exactly what I want. I can't be calm when I see this debug info ;)
My CustomCell class looks like that:
class CustomCell: UITableViewCell {

//MARK: - Outlets

@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!

//MARK: - Variables

var dream: MyDream? {
    didSet {
        if let item = dream, let image = UIImage(data: item.photoData) {
            scaleImageView(image: image)
            photoImageView.image = image
            titleLabel.text = item.title
        }
    }
}

func scaleImageView(image: UIImage) {
    let imageWidth = image.size.width
    let imageScale = image.size.height / image.size.width
    if imageWidth > photoImageView.bounds.width {
        heightConstraint.constant = photoImageView.bounds.size.width * imageScale
    } else {
        heightConstraint.constant = imageWidth * imageScale
    }
}
}

my cell in .xib looks like that:

TitleLabel doesn't have a height constraint. Leading, Top, Trailing, Bottom only.

and my ViewController is quite simple and looks like that:
class ViewController: UIViewController {

//MARK: - Outlets

@IBOutlet var tableView: UITableView!

//MARK: - Variables

lazy var dreams = [MyDream]()

override func viewDidLoad() {
    super.viewDidLoad()
    createModel() // I mock data here :)
    setTableView()
}

func setTableView() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.register(UINib(nibName: String(describing: CustomCell.self), bundle: nil), forCellReuseIdentifier: "cell")
}

func createModel() {
    for i in 0..<12 {
        if i < 6 {
            if let image = UIImage(named: "\(i + 1)"), let imageData = UIImageJPEGRepresentation(image, 100) {
                let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
                dreams.append(dream)
            }
        } else {
            if let image = UIImage(named: "\(i - 5)"), let imageData = UIImageJPEGRepresentation(image, 100) {
                let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
                dreams.append(dream)
            }
        }
    }
}

}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dreams.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
    cell.dream = dreams[indexPath.row]
    cell.selectionStyle = .none
    return cell
}

}

How it looks like in simulator:

every thing look fine, but console gives me this kind of error:

I don't know why? I tried to use layoutIfNeeded(), updateConstraints() and setNeedsLayout() in didSet in CustomCell but is doesn't help. Any suggestions?

A: I guess you're having some redundant constraints on your image.
They could be height / bottom / top constraints. One should be removed


text:
Q: Does matrix multiplication distribute over blocks? Does matrix multiplication distribute over blocks?
In other words, does $A[B|C] = [AB|AC]$? And does this generalizes to a block partition that is more than one block tall? That is does
$$
X
\begin{bmatrix}
    A & B & \\
    D & C &
\end{bmatrix}
=
\begin{bmatrix}
    XA & XB & \\
    XD & XC &
\end{bmatrix}
$$
(Note the written out matrix is a block matrix; I just didn't figure out how to draw lines between the blocks in latex.)
I believe that the column situation is true, but I am less confident about the 2D block case.

A: Yes for $A[B|C]=[AB|AC]$. This is due in definition of of multiplication say $D=EF$, $D_{ij}=\sum_{k=1}^n E_{ik}F_{kj}$, here $F_{kj}$ just involves elements from the $j$ columns and not any other columns.
The block matrix case is not a valid multiplication.
Suppose $A$ and $D$ both have $n$ rows each, then on the left hand side $X$ has $2n$ columns, but on the right hand side $X$ has $n$ columns.

A: Well, for the matrix product to be defined, there are constraints on the dimensions of the matrices involved. It's easy to see that these constraints fail in the second case.


text:
Q: Is it possible to train on bosses using weapons other than the dagger? Boss fight practice uses the dagger. Considered that it's perhaps the single worst weapon, that makes some sense. However, this probably result in the developing of strategies that work when you have the dagger but are disastrous when you don't.
For example, the best thing to do for King Conga 3 seems to be rushing to the center. That probably won't work if I have a whip, however. I don't know; I probably would have to find myself in such a situation in a real game to know just how terribly wrong that plan can go.
Is there a way to change equipment in boss (and miniboss, and enemy) training?

A: The game now features a built-in way to do so. You can unlock the Swordmaster by buying a golden key in 2-2 for 400 gold (or at least, that's how I did it.)

From here you can bring any weapon to the training areas. Jump on one of the buttons to change the material of your current weapon.

A: New Answer: YES, and it's not difficult to do now.
Note: Look in the edit history to see the old answers.
Since Necrodancer's release, there is now an NPC available called the "Weapommaster" that will swap out your weapons for training. You need to buy him for 400 gold from Zone 2.


text:
Q: The schema in this data file must match the datasource : Amazon Machine Learning When i create a model (regression) using Amazon Machine Learning,  i provide a datasource with some schema. The data source contains some values along with the target attribute. Then the data source is splitted in 70-30 for training and evaluation of model and they still need target attribute with values in it. As the data will be used for training first and then for evaluation so the target attribute is required, this much i understand.
Now come to the batch prediction part. In this also i have to provide a datasource and i understand that the schema have to be similar to the schema which is used to train the model, so again the target attribute is required but why the values are required in this part i do not understand. If i provide a dataset with similar schema and no data in target attribute it gives me
 The schema in this data file must match the datasource used to create the ML model ml-KSc8japCCo0. Ensure that the data file you are using matches the schema structure.

When i use the same schema with same model but with values in target attribute everything works fine.

A: You needs to provide a batch with all the values to make the prediction less the field to predict; for example,
I used this structure to make de model and the training, select seconds_taken like a target
serial,operator,station,phase,next_phase,seconds
123,Jack,Machine 1,Phase 1,Phase 2,230528

The goal is make a prediction about how many time is gonna take to pass from the first phase to another with a different values of operator and station, to detect better performance on the company.
Select your evaluation on the Machine Learning Dashboard
Machine Learning -> Batch Predictions -> Create batch prediction
This is the structure to make a prediction:
serial,operator,station,phase,next_phase
123,Benn,Machine 1,Phase 1,Phase 2
123,Jhon,Machine 1,Phase 1,Phase 2
123,Benn,Machine 2,Phase 1,Phase 2
123,Jhon,Machine 2,Phase 1,Phase 2

Take care on the titles, I got the same error if I use this structure
serial,operator,station,phase,next_phase,seconds
123,Benn,Machine 1,Phase 1,Phase 2
123,Jhon,Machine 1,Phase 1,Phase 2
123,Benn,Machine 2,Phase 1,Phase 2
123,Jhon,Machine 2,Phase 1,Phase 2


text:
Q: BASH - can't find what the $? special variable means Anyone knows what $? means in BASH?
I have to write a script that restarts a process if it crashes or is killed.  So I found this to start from :
RESTART="/etc/init.d/apache2 restart"
if [ $? -ne 0 ] # if apache not running
then
   # restart apache
   $RESTART
fi

I have done a search, but $? eludes me.
I am not sure if the above script is the best way to do this, I am assuming that $RESTART will hang until the process is killed or dies? If not, I would assume there would be some kind of sleep() call in there so this thing doesn;t spin at 1000 miles per hour.

A:
Anyone know what $? means in bash

It's the exit status of the most recently executed command.
[cnicutar@fresh ~]$ ls /nothing
ls: cannot access /nothing: No such file or directory
[cnicutar@fresh ~]$ echo $?
2

[cnicutar@fresh ~]$ ls -ld .
drwx------ 15 cnicutar users 4096 Aug 16 15:29 .
[cnicutar@fresh ~]$ echo $?
0

Look it up at tldp.

A: Q: cant find what bash $? means
A: It's the "return status" of the program.
/* In this example, "$?" from "./hello" will be "0": Status == OK */
#include <stdio.h>

int main (argc, char*argv[])
{
  printf ("Hello world!\n");
  return 0;
}

Here is a list of "special shell variables":

*

*http://unixhelp.ed.ac.uk/scrpt/scrpt2.2.2.html


text:
Q: ListView with CursorLoader and SimpleCursorAdapter isn't displaying data I'm trying to populate a ListView with data from a query using a CursorLoader. I'm new to CursorLoaders and I'm using code I purloined from Beginning Android 4 Application Development. As you can see, I'm getting data from an Intent. The data in the Intent is what I want; I've verified that in the debugger. However, when I query my database, nothing displays in the ListView. Can anyone help?
public class MyList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {

private static final String TABLE_BASEPATH = "tbl";
private static final String AUTHORITY = "SQLData";
public static final Uri MY_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_BASEPATH);

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent myData = getIntent();
    Bundle info = myData.getExtras();

    if (info != null){
        Cursor c;
        String[] dataColumns = { "mycolumn" };
        String selection = "level = '" + info.getString("Level") + "'";

        if (android.os.Build.VERSION.SDK_INT < 11)
            c = managedQuery(MY_URI, dataColumns, selection, null, "ORDER BY mycolumn");
        else
        {
            CursorLoader cursorloader = new CursorLoader(this, MY_URI, dataColumns, selection, null, "ORDER BY mycolumn");
            c = cursorloader.loadInBackground();
        }

        int[] viewIDs = { R.id.mylist1 };
        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT < 11)
            adapter = new SimpleCursorAdapter(this, R.layout.mylist, c, dataColumns, viewIDs);
        else
            adapter = new SimpleCursorAdapter(this, R.layout.mylist, c, dataColumns, viewIDs, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        this.setListAdapter(adapter);
    }
}

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, MY_URI,
            PROJECTION, null, null, null);
}

public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    switch (loader.getId()) {
      case LOADER_ID:
        mAdapter.swapCursor(cursor);
        break;
    }

}

public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);

}

It doesn't matter if I'm using the cursor or the CursorLoader. If my version is < 11 (cursor), I get no data; if it's > 11 (CursorLoader) I still get no data.

A: You need to put in the id column in the projection when working with ContentProviders, otherwise they "won't work". Which I think you are doing > api level 11...
String[] dataColumns = { "mycolumn" };

The above code should include the id field. If the id field is "_id" (like Sams answer):
String[] dataColumns = { "mycolumn", "_id" };


text:
Q: Ruby empty array changes values in iterations because of another array An empty array is defined outside a block and within the block, it is assigned to a new variable. If the new array changes, the empty array also modifies its values. Why?
# THIS CODE CHECK WHICH LETTERS IN klas APPEAR IN docs
klas = ["a", "b", "c"]

docs = [[1, "a"], [2, "a"], [3, "b"], [4, "b"], [5, "c"], [6, "c"]]

output = []
empty_array = Array.new(klas.size) { 0 } # EMPTY ARRAY DEFINED HERE

docs.each do |doc|
    puts empty_array.inspect
    puts (output_row = empty_array).inspect # EMPTY ARRAY ASSIGNED TO ANOTHER

    # FIND INDEX OF THE LETTER IN klas FROM docs. ASSIGN 1.
    output_row[klas.index(doc[1])] = 1 # PROBLEM! THIS ALSO CHANGES THE EMPTY ARRAY VALUES
    output << output_row
end

CONSOLE OUTPUT to show empty array changing its value based on another array
###
empty_array is [0, 0, 0]
output_row is [0, 0, 0]
---
###
empty_array is [1, 0, 0]
output_row is [1, 0, 0]
---
###
empty_array is [1, 0, 0]
output_row is [1, 0, 0]
---
###
empty_array is [1, 1, 0]
output_row is [1, 1, 0]
---
###
empty_array is [1, 1, 0]
output_row is [1, 1, 0]
---
###
empty_array is [1, 1, 1]
output_row is [1, 1, 1]
---

# INCORRECT output IS
=> [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
# SHOULD BE
=> [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]

But if the empty array is defined within the block and assigned to a new variable it works as expected.
docs.each do |doc|
    empty_array = Array.new(klas.size) { 0 } # THIS MAKES SURE empty_array stays with zero values
    output_row = empty_array
    output_row[klas.index(doc[1])] = 1
    output << output_row
end

CORRECT output IS
=> [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]

Why is the empty array modifying its value when it is outside a block? Shouldn't it remain the same irrespective of another array changing its value?

A: By using
output_row = empty_array

you are not copying the empty array. You are creating a reference to the same underlying array that is referenced in empty_array.
You can create a clone or a duplicate of the array. So use:
output_row = empty_array.dup

This will create a new Array, which is a duplicate of empty_array, see http://ruby-doc.org/core-2.4.1/Object.html#method-i-dup
A more complete explanation on what happens with an example:
a = [1] => [1] # is creating a new array 'x'
               # a is referencing this array, a is not the array itself!

b = a   => [1] # b now references the array 'x'

a = [2] => [2] # is creating a new array 'y', a is referencing this new array
               # the reference of b is not changing

b       => [1] # b still pointing to array 'x'

So with b = a you just tell them to reference the same array x, but b is not a reference to a.


text:
Q: Why threads are showing better performance than coroutines? I have written 3 simple programs to test coroutines performance advantage over threads. Each program does a lot of common simple computations. All programs were run separately from each other. Besides execution time I measured CPU usage via Visual VM IDE plugin.

*

*First program does all computations using 1000-threaded pool. This piece of code shows the worst results (64326 ms) comparing to others because of frequent context changes:
val executor = Executors.newFixedThreadPool(1000)
time = generateSequence {
  measureTimeMillis {
    val comps = mutableListOf<Future<Int>>()
    for (i in 1..1_000_000) {
      comps += executor.submit<Int> { computation2(); 15 }
    }
    comps.map { it.get() }.sum()
  }
}.take(100).sum()
println("Completed in $time ms")
executor.shutdownNow()

*Second program has the same logic but instead of 1000-threaded pool it uses only n-threaded pool (where n equals to amount of the machine's cores). It shows much better results (43939 ms) and uses less threads which is good too.
val executor2 = Executors.newFixedThreadPool(4)
  time = generateSequence {
  measureTimeMillis {
    val comps = mutableListOf<Future<Int>>()
    for (i in 1..1_000_000) {
      comps += executor2.submit<Int> { computation2(); 15 }
    }
    comps.map { it.get() }.sum()
  }
}.take(100).sum()
println("Completed in $time ms")
executor2.shutdownNow()

*Third program is written with coroutines and shows a big variance in the results (from 41784 ms to 81101 ms). I am very confused and don't quite understand why they are so different and why coroutines sometimes slower than threads (considering small async calculations is a forte of coroutines). Here is the code:
time = generateSequence {
  runBlocking {
    measureTimeMillis {
      val comps = mutableListOf<Deferred<Int>>()
      for (i in 1..1_000_000) {
        comps += async { computation2(); 15 }
      }
      comps.map { it.await() }.sum()
    }
  }
}.take(100).sum()
println("Completed in $time ms")

I actually read a lot about these coroutines and how they are implemented in kotlin, but in practice I don't see them working as intended. Am I doing my benchmarking wrong? Or maybe I'm using coroutines wrong?

A: The way you've set up your problem, you shouldn't expect any benefit from coroutines. In all cases you submit a non-divisible block of computation to an executor. You are not leveraging the idea of coroutine suspension, where you can write sequential code that actually gets chopped up and executed piecewise, possibly on different threads.
Most use cases of coroutines revolve around blocking code: avoiding the scenario where you hog a thread to do nothing but wait for a response. They may also be used to interleave CPU-intensive tasks, but this is a more special-cased scenario.
I would suggest benchmarking 1,000,000 tasks that involve several sequential blocking steps, like in Roman Elizarov's KotlinConf 2017 talk:
suspend fun postItem(item: Item) {
    val token = requestToken()
    val post = createPost(token, item)
    processPost(post)
}

where all of requestToken(), createPost() and processPost() involve network calls.
If you have two implementations of this, one with suspend funs and another with regular blocking functions, for example:
fun requestToken() {
   Thread.sleep(1000)
   return "token"
}

vs.
suspend fun requestToken() {
    delay(1000)
    return "token"
}

you'll find that you can't even set up to execute 1,000,000 concurrent invocations of the first version, and if you lower the number to what you can actually achieve without OutOfMemoryException: unable to create new native thread, the performance advantage of coroutines should be evident.
If you want to explore possible advantages of coroutines for CPU-bound tasks, you need a use case where it's not irrelevant whether you execute them sequentially or in parallel. In your examples above, this is treated as an irrelevant internal detail: in one version you run 1,000 concurrent tasks and in the other one you use just four, so it's almost sequential execution.
Hazelcast Jet is an example of such a use case because the computation tasks are co-dependent: one's output is another one's input. In this case you can't just run a few of them until completion, on a small thread pool, you actually have to interleave them so the buffered output doesn't explode. If you try to set up such a scenario with and without coroutines, you'll once again find that you're either allocating as many threads as there are tasks, or you are using suspendable coroutines, and the latter approach wins. Hazelcast Jet implements the spirit of coroutines in plain Java API.  Its approach would hugely benefit from the coroutine programming model, but currently it's pure Java.
Disclosure: the author of this post belongs to the Jet engineering team.

A: Coroutines are not designed to be faster than threads, it is for lower RAM consumption and better syntax for async calls.

A: Coroutines are designed to be lightweight threads. It uses lower RAM, because when you execute 1,000,000 concurrent routines, it doesn't have to create 1,000,000 threads. Coroutine can help you to optimise the threads usage, and make the execution more efficiency, and you don't need to care about the threads anymore. You can consider a coroutine as a runnable or task, which you can post into a handler and executed in a thread or threadpool.


text:
Q: Kotlin - Multiple animations at the same time and/or repeating after each other I am trying to create a game app in Android Studio. The concept is: there are circles falling down and you need to click/press them to make them disappear before touching a line at the bottom of the screen. To do this I create an ImageView with a circle as an image. I have it appear at the top and it moves down at a slow speed. When I press it, it disappears. The problem is, the second circle appears after the first which is good, but the downwards animation is not starting and the OnClickListener is not working either.
Here is the code for the creation of a circle:
/*Creation of ball via imageView.
ImageView is created on the current Activity Layout with the circle as image.
ImageView is 200x200 and appears in the middle of the screen (horizontal) on top.
*/
private fun drawBall(){
    val imageView = ImageView(this)
    imageView.setImageDrawable(getDrawable(R.drawable.ball_1))
    imageView.layoutParams = LinearLayout.LayoutParams(200, 200)
    imageView.x = (width/2.5).toFloat()
    layout.addView(imageView)
    moveBall(imageView)
}

Here is the code for the animation to start and the OnClickListener for the circle to disappear:
//Animation of ball falling down.
private fun moveBall(imageView: ImageView){
    val valueAnimator = ValueAnimator.ofFloat(0f, height*0.68.toFloat() )
    valueAnimator.addUpdateListener {
        val value = it.animatedValue as Float
        imageView.translationY = value
    }

    valueAnimator.interpolator = LinearInterpolator()
    valueAnimator.duration = 2500
    valueAnimator.start()

    //Shooting the ball and incrementing score
    imageView.setOnClickListener(){
        imageView.visibility = View.INVISIBLE
        var currentScore = textView_score.text.toString().toInt()
        currentScore++
        textView_score.text = currentScore.toString()
    }
}

Here you find the code where I'm trying to create multiple instances of a circle to fall down:
//Multiple instances of the falling ball animation.
private fun startBalls(){
    val runnable = Runnable { drawBall() }
    runnable.run(){
        drawBall()
    }

    val exec = ScheduledThreadPoolExecutor(1)
    val period : Long = 1000
    exec.scheduleAtFixedRate(runnable,0, period, TimeUnit.MILLISECONDS)
    val delay : Long = 1000
    exec.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.MILLISECONDS)
}

I think my main problem is where I'm trying to create the multiple instances of the circles.
Thank you in advance.

A: Logging from moveBall() shows that the code is not executed on the UI thread when the Runnable is started by the ScheduledThreadPoolExecutor. More specifically, the next line after  valueAnimator.start() is not executed at all (the first time you "touch" a UI element causes an Exception in the non-UI thread"), so the OnClickListener is not set for all but the first ImageView.
Since it also seems to be a problem when the same instance of a Runnable is reused with ScheduledThreadPoolExecutor, you can use a custom Runnable class and have it invoke  drawBall() on the UI thread:
class MyRunnable(val functionToInvoke: () -> Unit): Runnable {
    override fun run() {
        Handler(Looper.getMainLooper()).post(Runnable {
            //this will run on the UI thread
            functionToInvoke.invoke()
      })
    }
}

Usage in startBalls():
val exec = ScheduledThreadPoolExecutor(1)
val period : Long = 1000
exec.scheduleAtFixedRate(MyRunnable({drawBall()}),0, period, TimeUnit.MILLISECONDS)
val delay : Long = 1000
exec.scheduleWithFixedDelay(MyRunnable({drawBall()}), 0, delay, TimeUnit.MILLISECONDS)


text:
Q: Web API 2 Receiving Json Can anyone give me example of sending json data from jquery ajax to web api controller, both client and server code? For instance I want to send {Name: "SomeName", Email: "SomeEmail"} through ajax as post request and to get those values at controller...

A: Server side to retrieve values:
public class RequestModel()
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public MyWebApiController : ApiController
{
    public object Post(RequestModel model)
    {
        // Do something
        // Return same values back
        return model;
    }
}

Client side to post values:
$.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/Api/MyWebApi',
    data: { Name = "Bob", Email = "bob@example.com" },
    success: function (responseData) {

         // Do something on success, with the returned data
         alert("Email:" + responseData.Email + ", Name:" + responseData.Name);

    },
    error: function (jqXHR, textStatus, errorThrown) {

         // Display error?
    }
})


text:
Q: is Math.round or Date different for firefox? Is Math.round different for firefox? Or is Date different?
var p = Math.round(((today - start) / (end - start)) * 100);

In firefox p is "N/A" in crome it is a normal number. Why?
today, start and end are all Date objects.

A: Math.round() takes a number as parameter. Giving it a Date object does not make sense. See reference and/or the ECMAScript spec.
Before calculating you should decide which unit you are operating on.  Nanoseconds, milliseconds, seconds, hours,...?
For example, to get the milliseconds portion of the today date object in universal time you can use:
var milliseconds = today.getUTCMilliseconds();

A: Why? Because Firefox has - in this case - implemented closer to the ECMAScript specs.


text:
Q: Setting up exceptions I am having trouble understanding how to do the following step in my assignment, I am to
What does it mean to have an Exception superclass constructor? Where would i put that?
here is just the EmptyFieldException class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EmptyFieldException

{
  EmptyFieldException()
  {

  }

}

here is my application where most of the work is done
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;

public class AccountApplet extends JApplet implements ActionListener
{
  //  For West
  public JLabel  ai       = new JLabel("Account ID ");
  public JTextField  aitf = new JTextField();
  public JLabel  ab       = new JLabel("Account Balance ");
  public JTextField  abtf = new JTextField();

  //  For East
  public JButton     dp   = new JButton ("Deposit");
  public JTextField  dptf = new JTextField();
  public JButton       wt = new JButton ("Withdraw");
  public JTextField  wttf = new JTextField();

  // For South
  public JLabel  status   = new JLabel("placeholder");

  public void init()
  {
    this.setSize(400, 90);

    //----------------------
    //  Set up the Structure
    //----------------------

    Container      c = getContentPane();
    JPanel         b = new JPanel(new BorderLayout());
    JPanel      west = new JPanel(new GridLayout(2,2));
    JPanel      east = new JPanel(new BorderLayout());
    JPanel depo_with = new JPanel(new GridLayout(2,2));

    // Add BorderLayout to the container
    c.add(b);

    // Add everything to West
    b.add(west, BorderLayout.WEST);

    west.setBorder(new TitledBorder("Display Account Information"));
    west.add(ai);
    west.add(aitf);
    aitf.setEditable(false);
    west.add(ab);
    west.add(abtf);
    abtf.setEditable(false);

    // Add everything to EAST
    b.add(east, BorderLayout.EAST);

    east.setBorder(new TitledBorder("Deposit or Withdrawl Funds"));

    east.add(depo_with, BorderLayout.EAST);

    depo_with.add(dptf);
    depo_with.add(dp);
    depo_with.add(wttf);
    depo_with.add(wt);

    dp.addActionListener(this);
    wt.addActionListener(this);

    // Add everything to EAST
    b.add(status, BorderLayout.SOUTH);

  }  // End intit

  public void actionPerformed(ActionEvent e)
  {
    if (e.getSource() == dp)  //  Executes if deposit was clicked
    {
    }

    if (e.getSource() == wt)  //  Executes if withdraw was clicked
    {
    }
  }  // End actionPerformed

  public void refreshFields()
  {
    // diplays accound id and balance in left text fields
    //should be called when the applet is first displayed and after each valid transaction
  }

  public double getAmount(JTextField tf) //throws EmptyFieldException,
                                         //       NumberFormatException,
                                         //       NegativeAmountException
  {
    return 5.0;
  }  //  End getAmount

} // End Class

A: Calling a superclass's constructor is done with the super keyword:

... pass a message to the Exception superclass constructor.

public class MyException extends Exception { // Exception is the superclass

    public MyException() {
        super("My Message"); // call Exception's constructor
    }

}

The superclass constructor is always called when calling a classes constructor (except maybe for Object).
Though, if the superclass constructor has no arguments, you don't have to call super() explicitly.
It should also be noted that the call to the superclass constructor must always be the first statement in a constructor.


text:
Q: Waterline BIGINT type with sails-mysql I would like to know how can i define a bigint type in a waterline model using sails-mysql? Couldn't find any proper documentation about it. Seems like it doesn't support bigint types however i really need it. Trying to dig over the sourcecode i found something liek this:
https://github.com/balderdashy/sails-mysql/blob/987f4674785970951bc52becdfdb479864106da1/helpers/private/schema/build-schema.js#L29
But it's still not working.
module.exports = {
    attributes: {

        userId: {
            type: 'bigint',
            autoIncrement: true,
            primaryKey: true,
            unique: true,
        },
   }
};

This one still keeps creating an integer field in the database.

A: Ok after digging through the source code a bit more i figured that i have to set an extra property called size for the field. Setting it to 64 will cause waterline to create a BIGINT field.
module.exports = {
    attributes: {

        userId: {
            type: 'integer',
            size: 64, // waterline will translate this as bigint
            autoIncrement: true,
            primaryKey: true,
            unique: true,
        },
   }
};

A: Another way is to use the following attributes:
{
   type: 'string',
   columnType: 'bigint'
}

This ignores Waterline data types and forces Postgres/MySQL column data type directly.

A: Edit: I hadn't tested this thoroughly. It isn't working, after all.
The property size isn't allowed for model attributes in Sails v1.0+, but this seems to work. I pulled it from the definition of the createdAt attribute in the waterline library (line 485, as of this writing).
module.exports = {
  attributes: {
    timeOfDay: {
      type: 'number',
      autoMigrations: { columnType: '_numbertimestamp' }
    }
  }
};


text:
Q: Is there any easy way to export user input into a text file? Preferably in the same class?
I tried this: http://mrbool.com/how-to-store-data-with-java/25483
but it was to hard to manipulate my data.
Are there any other easier ways?
Thanks for any suggestions

A: Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
PrintWriter p = new PrintWriter("outputFile.txt");
p.println(s);
...
p.close();

Scanner can grab user command-line input and store it as a String, which can easily be sent to a file.

A: I don't know if this is anything like what you're after, but ...
package test;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Test {

  static String endOfInputDelimiter = "/";

  public static void main(String[] args) throws FileNotFoundException  {

    Scanner scan = new Scanner(System.in);
      PrintWriter p = new PrintWriter("outputFile.txt");
        while(scan.hasNext()){
          String s = scan.nextLine();
          if(s.equals(endOfInputDelimiter))
            break;
          p.println(s);
        }
      p.close();
    scan.close();
  }
}

It's pretty hokey; I especially don't like the "if...break", but maybe it's a start for you.


text:
Q: how to insert the data from a text file to a python programme This is the exact code in python3 for a wikimedia project on Jupyter
import pywikibot

site = pywikibot.Site('ta', 'wikisource')
page = pywikibot.Page(site, 'Index:தந்தை பெரியார் சிந்தனைகள்.pdf')
page.text = page.text.replace('பேராசிரியர் ந. சுப்புரெட்டியார்','மின்னூல்கள்-பொதுகள உரிமம்-த. இ. க. க. 2015')
page.save()

In the above code, i want to change the pdf name one by one from a text file(book-list) and finally,  i want to save. To save manually, i am using shif+enter. How to automate my cotributions?
Here is the example of pdf name as in text file namely book-list which is having more than 2200 pdfs.

Index:அகத்திணைக் கொள்கைகள்.pdf
Index:அண்ணல் அநுமன்.pdf
Index:அணுக்கரு பௌதிகம்.pdf

A: Finally i extended the above code as follows;-
import csv
import pywikibot
with open('list-book-parameters.csv', 'r') as csvfile:
    reader = csv.reader(csvfile,delimiter="~")
    for row in reader:
      if len(row) == 8:
       if not 'booktitle' in row:
        booktitle=row[0]
        #print (row[0])
        site = pywikibot.Site('ta', 'wikisource')
        page = pywikibot.Page(site, 'Index:' + booktitle + '.pdf')
        page.text = page.text.replace('old data','new data')
        page.save()

The data in the list-book-parameters.csv as follows;-
booktitle~version~publisher~press~date~place~coverpage~category

--solved myself ;)


text:
Q: AJAX Live Search showing results ONLY if it starts with the same first letter I have a ajax live search bar that I made using this w3school example. http://www.w3schools.com/php/php_ajax_livesearch.asp
How do I get it to only show results that have the letters in the same order beginning with the first letter, as opposed to matching any chunk of letters in the word. For example, for the "COMPUTER" to be shown as a result you have to have typed "COM..." as opposed to "PUTER".
I believe i have narrowed it down to being somwhere in here:
//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
  {
  $y=$x->item($i)->getElementsByTagName('title');
  $z=$x->item($i)->getElementsByTagName('url');
  if ($y->item(0)->nodeType==1)
    {
    //find a link matching the search text
    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
      {
      if ($hint=="")
        {
        $hint="item(0)->childNodes->item(0)->nodeValue .
        "' target='_blank'>" .
        $y->item(0)->childNodes->item(0)->nodeValue . "";
        }
      else
        {
        $hint=$hint . "item(0)->childNodes->item(0)->nodeValue .
        "' target='_blank'>" .
        $y->item(0)->childNodes->item(0)->nodeValue . "";
        }
      }
    }
  }
}

A: Check your conditional syntax that search for items:
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))

this is making the search $q in any part of item, what you want to do is to search only if it begins with $q , so you have to change syntax:
if (strpos(strtolower($y->item(0)->childNodes->item(0)->nodeValue), strtolower($q)) === 0)

So now it will search if matches at the beginning (position === 0). You also notice that I use strtolower() in both compared values, this is because strpos() is case sensitive, and stristr() isn't.
Could you try now changing this line and tell us if it worked?


text:
Q: UNITY CS1061 Sprite does not contain definition for enabled I am following a tutorial on 2048 in unity. He is using a Text and Image to render his 'tiles' and I decided to use a sprite because I have pre-made tiles in adobe. The first bit of code is the TileStyleHolder and the second script is called Tile(to be attached to the actual sprite/image itself that will be enabled/disabled.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class TileStyle
{
    public Sprite tile_number;
}

public class TileStyleHolder : MonoBehaviour
{
    //SINGLETON
    public static TileStyleHolder Instance;

    public TileStyle[] TileStyles;

    void Awake()
    {
        Instance = this;
    }
}

AND THIS IS THE SECOND SCRIPT~~
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Tile : MonoBehaviour
{
    public int Number
    {
        get
        {
            return number;
        }
        set
        {
            number = value;
            if (number == 0)
                SetEmpty();
            else
            {
                ApplyStyle(number);
                SetVisible();
            }
        }
    }
    private int number;

    private Sprite TileSprite;

    void Awake()
    {
        TileSprite = transform.Find("numcell").GetComponent<Sprite>();
    }

    void ApplyStyleFromHolder(int index)
    {
        TileSprite = TileStyleHolder.Instance.TileStyles[index].tile_number.ToSprite();
    }

    void ApplyStyle(int num)
    {
        switch (num)
        {
            case 2:
            ApplyStyleFromHolder(0);
            break;

            case 4:
            ApplyStyleFromHolder(1);
            break;

            case 8:
            ApplyStyleFromHolder(2);
            break;

            case 16:
            ApplyStyleFromHolder(3);
            break;

            case 32:
            ApplyStyleFromHolder(4);
            break;

            case 64:
            ApplyStyleFromHolder(5);
            break;

            case 128:
            ApplyStyleFromHolder(6);
            break;

            case 256:
            ApplyStyleFromHolder(7);
            break;

            case 512:
            ApplyStyleFromHolder(8);
            break;

            case 1024:
            ApplyStyleFromHolder(9);
            break;

            case 2048:
            ApplyStyleFromHolder(10);
            break;

            case 4096:
            ApplyStyleFromHolder(11);
            break;

            default:
            Debug.LogError("Check the numders that you pass to ApplyStyle");
            break;
        }
    }

    private void SetVisible()
    {
        TileSprite.enabled = true;
    }

    private void SetEmpty()
    {
        TileSprite.enabled = false;
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

A: If you're using an Image component you can reference the sprite with:
Sprite mySprite = GetComponent<Image>().sprite;

If you're using a SpriteRenderer componenent you can reference the sprite with:
Sprite mySprite = GetComponent<SpriteRenderer>().sprite;


text:
Q: Size of the sparse vector in the column of a data-frame in Apache scala spark I am using a vector assembler to transform a dataframe.
var stringAssembler = new VectorAssembler().setInputCols(encodedstringColumns).setOutputCol("stringFeatures")
df = stringAssembler.transform(df)
**var stringVectorSize = df.select("stringFeatures").head.size**
var stringPca = new PCA().setInputCol("stringFeatures").setOutputCol("pcaStringFeatures").setK(stringVectorSize).fit(output)

Now stringVectorSize will tell PCA how many columns to keep while performing pca.
I am trying to get the size of the output sparse vector from the vector assembler but my code gives size = 1 which is wrong. What is the right code to get the size of a sparse vector which is the part of a dataframe column.
To put it plainly
+-------------+------------+-------------+------------+---+-----------+---------------+-----------------+--------------------+
|PetalLengthCm|PetalWidthCm|SepalLengthCm|SepalWidthCm| Id|    Species|Species_Encoded|       Id_Encoded|      stringFeatures|
+-------------+------------+-------------+------------+---+-----------+---------------+-----------------+--------------------+
|          1.4|         0.2|          5.1|         3.5|  1|Iris-setosa|  (2,[0],[1.0])| (149,[91],[1.0])|(151,[91,149],[1....|
|          1.4|         0.2|          4.9|         3.0|  2|Iris-setosa|  (2,[0],[1.0])|(149,[119],[1.0])|(151,[119,149],[1...|
|          1.3|         0.2|          4.7|         3.2|  3|Iris-setosa|  (2,[0],[1.0])|(149,[140],[1.0])|(151,[140,149],[1...|

For the above dataframe . I want to extract the size of stringFeatures sparse vector ( which is 151)

A: If you read DataFrame's documentation you will notice that the head method returns a Row. Therefore, rather than obtaining your SparseVector's size, you are obtaining Row's size. Thus, to solve this you have to extract the element stored in the Row.
val row = df.select("stringFeatures").head
val vector = vector(0).asInstanceOf[SparseVector]
val size = vector.size

For instance:
import sqlContext.implicits._
import org.apache.spark.mllib.linalg.SparseVector

val df = sc.parallelize(Array(10,2,3,4)).toDF("n")
val pepe = udf((i: Int) => new SparseVector(i, Array(i-1), Array(i)))
val x = df.select(pepe(df("n")).as("n"))

x.show()

+---------------+
|              n|
+---------------+
|(10,[9],[10.0])|
|  (2,[1],[2.0])|
|  (3,[2],[3.0])|
|  (4,[3],[4.0])|
+---------------+

val y = x.select("n").head

y(0).asInstanceOf[SparseVector].size
res12: Int = 10


text:
Q: Toast makeText can't resolve symbol "MyActivity.this" I was trying to set Toast, to show is registratiion was succesful of failed. But couldn't make it resolve the context. There is the code:
private void RegisterAccount() {
        String username = RegisterUsername.getText().toString();
        String mail = RegisterMail.getText().toString();
        String password = RegisterPassword.getText().toString();

    mAuth.createUserWithEmailAndPassword(mail, password)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {

                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if (task.isSuccessful()) {

                        User user = new User(username, mail);

                        FirebaseDatabase.getInstance().getReference("Users")

                                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())

                                .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {

                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if (task.isSuccessful()) {
                                    Toast.makeText(RegisterAccount.this, "Success", Toast.LENGTH_LONG).show();
                                }

                                else {
                                    Toast.makeText(RegisterAccount.this, "Failed", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }

                    else {
                        Toast.makeText(RegisterAccount.this, "Failed", Toast.LENGTH_LONG).show();
                    }
                }
            });

}

Error: Cannot resolve symbol 'RegisterAccount'
for all 3 Toast-s
I tried Toast.makeText(RegisterAccount(), "Failed", Toast.LENGTH_LONG).show();, RegisterAccount() instead of RegisterAccount.this and got error: Cannot resolve method 'makeText(void, java.lang.String, int)'.

A: You can try this:
Toast.makeText(requireActivity(), "Failed", Toast.LENGTH_LONG).show();

Or:
Toast.makeText(requireContext(), "Failed", Toast.LENGTH_LONG).show();


text:
Q: Using a var as a partial name? Im trying to render partials based upon a variable name, according to these docs the correct method is:

Subexpressions do not resolve variables so whichPartial must be a
  function. If a simple variable has the partial name, it's possible to
  resolve it via the lookup helper.

{{> (lookup . 'myVariable') }}

So I have tried:
{{#each index.types}}
    {{> (lookup . this.type) }}
{{/each}}

But I get the error:
Error: The partial undefined could not be found

I've also output the following in the loop:
{{this.type}}

The correct partial string is being read.

A: I had similar problem with using {{this}} as partial name. I managed to solve it by using partial block as follows:
{{#each this as |tab| }}
      {{> (tab)}}
{{/each}}

In your case you could try:
{{#each index.types as |item| }}
  {{> (item.type)}}
{{/each}}


text:
Q: Force WSUS to rescan WSUSContent folder I have a disconnected WSUS server. On my Internet-connected WSUS server, I performed an export. On the disconnected server, I performed an import, then copied the WSUSContent folder from the Internet-connected system to the disconnected system.
On the disconnected server, for the vast majority of updates, WSUS reports that "the files for this update have not yet been downloaded." When I click the file information, the files are present in the path listed.
I tried "wsusutil.exe reset", but that didn't fix the issue. It seems like the database simply won't check the file structure and see that the files are already there.
Any suggestions?


text:
Q: Как настроить подсветку sql запросов в phpstorm? Собственно вопрос, как настроить подсветку sql  функций в шторме ?

A: Вам нужно настроить Database компонент на ваш коннекшн:

View
  -> Tools Windows
  -> Database
  -> Add
  -> DataSource
  -> Mysql

Настраиваете параметры подключения к базе
Не забываем скачать Driver для MySQL
Проверить c помощью кнопки Test Connection
Если все ок, то во вкладке Schemas отметить схемы с которыми будете работать.
Ну и подождать пока подгрузится структура базы
P.S. После изменений в структуру, нужно рефрешнуть ее, а то оно в кеш складывает

A: File > Settings > Languages & Frameworks > Sql dialects > правая колонка


text:
Q: Returning dates in pyodbc using the cursor.execute select command I'm trying to use pyodbc to return dates that match certain criteria from an Oracle database. For example, I want to get all the dates between January 1, 2010 and January 1, 2011.
To do this I'm doing this:
x = cursor.execute("""select
    Column from Table where OutputDate > '2010/01/01' and OutputDate < '2011/01/01'"""
Something similar worked when I was using an Access database, but now it gives me this error:
pyodbc.DataError: ('22007', '[22007] [Microsoft][ODBC driver for Oracle][Oracle]ORA-01861: literal does not match format string (1861) (SQLExecDirectW)')
I'm on Windows 7 and the driver I'm using is Microsoft ODBC for Oracle (which I guess is obvious from the error)
Does "literal does not match format string" mean that I can't use < and > with dates on this database? Could anyone help me?
Thanks a lot,
Alex

A: Literal does not match format string means that you're trying to compare a date and a string. Change your query to the following and it should work.
select column
  from table
 where outputdate between to_date('2010/01/01','yyyy/mm/dd')
       and to_date('2011/01/01','yyyy/mm/dd')

Unless of course outputdate is not a date in which case it's best to transfer this into a date as well for your comparisions to work.
Note the between operator, which you can use in this situation.
There's a list of Oracle datatypes here; the site is good for everything.
I should add that I much prefer cx_Oracle for communicating with Oracle from python; though that is just personal preference.


text:
Q: Looking for QGIS equivalent of ArcGIS tool for buffering without polygons overlapping regions of neighboring boundaries Is there a way to create buffers around a group of polygons (vector file) in QGIS  where the overlapping buffer parts are not in the result? Please see picture example:
I've seen a question asked recently here about a method in ArcGIS, and it would be really good to know if there is any similar tool exists in QGIS or what would be the solution in QGIS? This was the question: Buffer Polygons without overlapping regions of neighbouring boundaries in ArcGIS Pro


text: Q: Sql Server 2012 Bulk Insert speed If I have a database on production with more that 50 applications using this database for read and write, does it slow bulk inserting (making use of SqlBulkCopy api in C#) of hundred of thousands of records in the database?