text:
Q: Dart - Error: Expected a declaration, but got '}' I cannot find the mistake in the below code. Dart shows an error message saying "Error: Expected a declaration but got '}'. Could someone please assist?

import 'package:http/http.dart';
import 'dart:convert';

class WorldTime {

  String location; // Location name for the UI
  String? time; // Time in that location
  String flag; // Url to an asset flag icon
  String url; // This is the location url for the API endpoint

  WorldTime({ required this.location, required this.flag, required this.url });

  }

  Future<void> getTime() async {

    var url;
    var response = await get(Uri.https('worldtimeapi.org', 'api/timezone/$url'));
    Map data = jsonDecode(response.body);
    // print(data);

    // get properties from data
    String datetime = data['datetime'];
    String offset = data['utc_offset'].substring(1,3);
    print(datetime);
    print(offset);

    // Create Datetime object
    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset)));

    // Set the time property
    var time = now.toString();

  }

}

A: There is a closing } after WorldTime constructor declaration, so that the last } in the code you given is extra. The solution is to remove the closing } after the WorldTime({ }); constructor declaration, or remove the last }.


text:
Q: My app is showing install size instead of download size in App Store My uploaded iOS app is showing 28.3 MB size in the App Store app on an iPhone 5s. As per the Estimated App Store file size from iTunes Connect, my app size will be as shown in the image.

My concern is that it is showing the install size (28.4 MB, the amount of disk space that the app will take on the customer's device) in the App Store app on the iPhone 5s.
I think it should be Download Size instead of Install Size. Is anything wrong with the size showing in the App Store? Or is it so?

A: The App Store shows the install size because this is the amount of storage space the user requires on the device once the app is installed. The download size is rarely useful. There is nothing you can do to change what is shown on the App Store page.

A: This is due to download size for different device is variant . So before build for appstore check that you are build for universal ipa.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AVX-512 - How to gather data from memory using assembly instruction? I'm trying to gather 64-bit integers from memory using the assembler instruction. Below you can see how I call assembly code from C. Please notice that assembly code uses NASM syntax.
nasm_gather.asm file
bits 64

        section .text
global nasm_gather:function

extern base_addr
extern vindex

nasm_gather:
        ; prolog
        push            rbp
        push            rbx
        push            r12
        push            r13

        mov             r12         ,[rel base_addr]                ; r12 point to base_addr
        mov             r13         ,[rel vindex]                   ; r13 points to vindex
        vmovdqu32       zmm1        ,[r13]                          ; zmm1 = [2, 5, 1, 3, 0, 4, 7, 6]
        vpxorq          zmm2        ,zmm2               ,zmm2       ; zmm2 = [0, 0, 0, 0, 0, 0, 0, 0]
        vpgatherqq      zmm2        ,[r12 + zmm1*8]                 ; ----> Illegal instruction at address = ...
        ...
        ; epilog
        pop             r13
        pop             r12
        pop             rbx
        pop             rbp
        ret

main.cpp file
#include <iostream>
#include <immintrin.h>

using namespace std;

extern "C" int nasm_gather();

const int N=32;
int64_t* base_addr /*__attribute__ ((aligned (64)))*/  = (int64_t *) malloc(sizeof(int64_t) * N);
int64_t* vindex =  (int64_t *) malloc(sizeof(int64_t) * 8);

int main() {
    /* initialize indices */
    vindex[0]=2; vindex[1]=5; vindex[2]=1; vindex[3]=3;
    vindex[4]=0; vindex[5]=4; vindex[6]=7; vindex[7]=6;
    // ...
    int64_t result = nasm_gather();
    ...

    return 0;
}

(vpgatherqq zmm, vm64z assembler instruction corresponds to the _mm512_i64gather_epi64 intrinsic function in C)
Just as the programm reaches this point:
vpgatherqq      zmm2        ,[r12 + zmm1*8]

I get the Illegal instruction error:

Illegal instruction at address = 4011f0: 62 d2 fd 48 91 14 cc 62 f1 7e
48 6f c2 e8 10
If you believe your application should attempt to
execute this illegal instruction (and others that may be present),
Then use this knob: -emit-illegal-insts 0 and this error message will
be avoided.

What's the problem?

A: Gathers need a mask (so they can record progress if interrupted, or if one element faults).  NASM normally doesn't let you assemble illegal instructions without a warning; it's a NASM bug that it doesn't help you spot this error.
Also, your entire approach of using globals instead of function args is bad for both maintainability and performance.  Use intrinsics like a normal person if you're already willing to tell GCC it can emit AVX-512 instructions (-march=skylake-avx512) and to #include <immintrin.h> in your source.  e.g. _mm512_mask_i64gather_epi64.  Calling any function at all instead of inlining the gather instruction is going to cost a significant fraction of the cost of a gather, and more than that if it's a clunky inefficient function written that way.  Gathers are pretty questionable if your indices aren't already in a SIMD vector, and it certainly doesn't help to use a pointer stored in a global var for the index, instead of passing a pointer arg for the gather function to load a vector of indices from somewhere.

The following code runs fine for me, in SDE 8.33.0, NASM 2.15.05.  You claim that adding {k1} doesn't fix the problem for you.  Either your version of SDE is broken, or you're doing something else wrong.  Or you forgot to rebuild your executable from the updated source.
default rel
global _start
_start:
    lea     rax, [rel buf]      ; dummy base = static array.  In a function, use RDI (first int/pointer arg)
    vpxor   xmm1, xmm1,xmm1     ; ZMM1 = dummy index = all zeros, efficiently done with a VEX-coded AVX instruction

    kxnorb      k1, k0,k0           ; mask = -1
    vpxor       xmm0, xmm0,xmm0     ; optional: dependency-breaking before merge-masking.  GCC will do this for the intrinsic.
    vpgatherqq  zmm0{k1}, [rax + zmm1*8]

    mov eax, 231
    syscall             ; exit_group(RDI)

section .bss
buf: resd 1024

I can reproduce that SDE error message if I remove the {k1}, making it unmasked like your original question.  NASM 2.15.05 errors if you try to use {k1}{z} - Gathers only support merge-masking (again so it can resume after a partial execution interrupted by a #PF or possibly interrupt).  But with correct source, it builds and runs just fine in a static executable.  The host CPU is an i7-6700k Skylake-client (which doesn't support AVX-512, so it's up to SDE to make it work).
$ nasm -felf64 avx512-gather.asm
$ ld -o avx512-gather avx512-gather.o
$ /opt/sde-external-8.33.0-2019-02-07-lin/sde64 -- ./avx512-gather
$ echo $?
0

(sde64 -icl works, too, of course.)
Linking the same machine code into a function callable from C++ would run the same way, but again, that would be pointless when you can use intrinsics (and disassemble with objdump -drwC -Mintel a.out to see how GCC used the instruction.)


text:
Q: Pytorch, pipenv and numpy support? I am using pytorch and installed it follow these instructions:
pipenv install git+https://github.com/pytorch/pytorch#egg=pytorch
pipenv install git+https://github.com/pytorch/vision#egg=torchvision

in order to install pytorch with pipenv. This runs some of the examples, but for instance, this MNIST code:
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable

# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                    help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                    help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                    help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
                    help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
                    help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                    help='how many batches to wait before logging training status')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()

torch.manual_seed(args.seed)
if args.cuda:
    torch.cuda.manual_seed(args.seed)

kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=args.test_batch_size, shuffle=True, **kwargs)

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.fc1 = nn.Linear(320, 50)
        self.fc2 = nn.Linear(50, 10)

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        x = x.view(-1, 320)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)

model = Net()
if args.cuda:
    model.cuda()

optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)

def train(epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        if args.cuda:
            data, target = data.cuda(), target.cuda()
        data, target = Variable(data), Variable(target)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.data[0]))

def test():
    model.eval()
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        if args.cuda:
            data, target = data.cuda(), target.cuda()
        data, target = Variable(data, volatile=True), Variable(target)
        output = model(data)
        test_loss += F.nll_loss(output, target, size_average=False).data[0] # sum up batch loss
        pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
        correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

for epoch in range(1, args.epochs + 1):
    train(epoch)
    test()

Does not run giving the error:
RuntimeError: PyTorch was compiled without NumPy support

Running:
pipenv install numpy

does not resolve the error. Is there a way to use pipenv and install pytorch with numpy support?

A: I managed to get it. I slightly changed:
pipenv install git+https://github.com/pytorch/pytorch#egg=pytorch
pipenv install git+https://github.com/pytorch/vision#egg=torchvision

To:
pipenv install http://download.pytorch.org/whl/cu91/torch-0.3.1-cp36-cp36m-linux_x86_64.whl
pipenv install git+https://github.com/pytorch/vision#egg=torchvision

The first command is what pytorch.org recomends when I select Linux, pip, python 3.6, and CUDA 9.1. For some reason, pipenv install torchvision doesn't work.
For reference here is the resulting Pipfile:
[[source]]

url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]

"633048b" = {file = "http://download.pytorch.org/whl/cu91/torch-0.3.1-cp36-cp36m
-linux_x86_64.whl"}
torchvision = {git = "https://github.com/pytorch/vision"}

[dev-packages]


text:
Q: Find one fake coin out of 14 in 3 scales There is a pile with 14 coins. One of them is fake and has a different weight than the others, which are the same.
Using a balance scale, find the fake coin with no more than 3 scales.

Based on the wiki article it is believed that no more than 13 coins can be tested with 3 scales, but I found a solution for 14 coins, and I wish to share it with you in my answer below.

A: Take two coins and slice them in half with equal weight.

*

*Scale 1: $3+0.5 + 0.5$ vs. $4$ -> Take 2 distinct half coins with 3 other coins, let's call it "pile A", and weigh them against 4 other coins. Let's call it "pile B". And we are leaving 5 coins on the side.

*If the scale is not balanced, it means that the 5 coins we didn't scale are not fake.

*

*Scale 2: $2 + 3B$ vs. $1 + 4R$ -> Take 2 coins from pile A with 3 coins from pile B and weight them against 1 coin from pile B and 4 real coins(those we didn't weight and we now know are not fake)

*There are three possible outcomes: the scale is flipped, the scale is balanced, or it didn't change. In all those cases, we left out with three coins where we know the relative weight of a fake coin.

*Scale 3: $1$ vs. $1$: Weight two of the coins in question, one against the other, leaving one aside. In the case of half coins, compare half and half coins. If the scale is balanced, then the fake coin is the one we put aside. Otherwise, we should know who is the fake coin from the scale result, as in this case, we know the relative weight of the fake coin.

*In case the scale is balanced, it means that the fake coin is among the 5 coins we didn't weight

*

*Scale 2: $2$ vs. $1 + 1R$ -> Take two coins, let's call it "pile A" and scale them against 1 coin and 1 real coin, let's call it "pile B".

*

*If the scale is balanced, then the fake coin is one of the 2 we didn't scale. Scale one of them with a real coin to find out who is the fake coin.

*Scale 3: $1 + 1B$ vs. $2R$ -> If the scale is not balanced, then scale one coin from pile A with one coin from pile B against two real coins. There could be three outcomes: The scale is balanced; the scale is flipped; the scale didn't change. That correlates with the 3 coins we have been testing to find the fake coin.


text:
Q: How do I get the browser to reload my script from the server each time the page is loaded? I currently call a Perl script from my website like this to produce a Captcha image like this:
<script language="JavaScript1.2" type="text/javascript" src="http://www.MyUrl/cgi-bin/Captcha-Image.pl"></script>

And I  return Captcha Image to the web page like this:
<script language="JavaScript" type="text/javascript">
                <!--
                document.write (CAPTCHA);
                //-->
              </script>

This works fine but the issue I'm having is if the user clicks back the Captcha image does not refresh and needs to do so, as after it is submitted it is no longer valid.
So I'm trying to use this:
<input type="hidden" id="refreshed" value="no"/>

<script type="text/javascript">

onload = function () {
  var e = document.getElementById("refreshed");
  if (e.value == "no") e.value = "yes";
  else { e.value = "no"; location.reload(); }
}

</script>

But instead of refreshing the page I would like to just recall the Perl script Im already using the "Cache-Control: no-cache tag" "http://www.MyUrl/cgi-bin/Captcha-Image.pl" to print a new image I tried this with no luck:
onload = function () {
  var e = document.getElementById("refreshed");
  if (e.value == "no") e.value = "yes";
  else { e.value = "no"; location.reload('http://www.MyUrl/cgi-bin/Captcha-Image.pl'); }
}


text:
Q: Android auto text reply using broadcast receiver sending multiple texts. The following code sends a text to the incoming calling number, however it sends a different amount of texts every time. Sometimes it only sends one, but it varies up to 6. When monitoring my code while it functions I also get different numbers of broadcasts. What am I doing wrong?
Receiver:
package com.biapps.makin_biscuits;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Jake on 3/21/2016.
 */

public class IncomingCallReceiver extends BroadcastReceiver {

private static final String TAG = "MyListener";
    private Context mContext;
    private Intent mIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;

        tm.listen(phoneStateListener, events);
    }

    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override

        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            Log.i(TAG, "number: " + incomingNumber + "");
            Toast.makeText(mContext,"Incoming Call: " + incomingNumber + "",Toast.LENGTH_LONG).show();
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                        SmsManager smsManager =     SmsManager.getDefault();
                        smsManager.sendTextMessage(incomingNumber, null, "I'm busy bruh", null, null);
                    TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
                    tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

            }

                   }
    };
}

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.biapps.makin_biscuits">
    <uses-sdk android:minSdkVersion="4" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ContactsList">
            <intent-filter>
                <category android:name="android.intent.category.ALTERNATIVE" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".IncomingCallReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
                <action android:name="android.intent.action.Trigger" />

            </intent-filter>
        </receiver>
    </application>

</manifest>

MainActivity:
package com.biapps.makin_biscuits;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    //set object labels and states here
    private ImageButton icon;
    private AudioManager am;
    private ImageButton people;
    private ImageButton ring;

    @Override

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

        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        icon = (ImageButton) findViewById(R.id.icon);
        icon.setOnClickListener(imgButtonHandler);
        people = (ImageButton) findViewById(R.id.people);
        //people.setOnClickListener(peopleButtonHandler);
        ring = (ImageButton) findViewById(R.id.ring);

    }

    int buttonstate = 0;
    public View.OnClickListener imgButtonHandler = new View.OnClickListener() {

        public void onClick(View v) {
            if (buttonstate == 0) {

                icon.setImageResource(R.drawable.buttonup);
                buttonstate = 1;
                am.setRingerMode(0);
                Toast.makeText(getApplicationContext(), "Go!!",
                        Toast.LENGTH_SHORT).show();

                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                intent.setAction("android.intent.action.Trigger");
                sendBroadcast(intent);
            } else {

                icon.setImageResource(R.drawable.button);
                buttonstate = 0;
                am.setRingerMode(2);
                Toast.makeText(getApplicationContext(), "Come back!!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
}

A: I added some code to recognize the previous state and determine whether or not to do the actions. This fixed the problem.
package com.biapps.makin_biscuits;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Jake on 3/21/2016.
 */

public class IncomingCallReceiver extends BroadcastReceiver {

private static final String TAG = "MyListener";
    private Context mContext;
    private Intent mIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;
        TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;

        tm.listen(phoneStateListener, events);
    }

    int previousState=TelephonyManager.CALL_STATE_OFFHOOK;
    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override

        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            int Call_State_Ringing = TelephonyManager.CALL_STATE_RINGING;
            int Call_State_OffHook = TelephonyManager.CALL_STATE_OFFHOOK;
            if (Call_State_Ringing == state && Call_State_OffHook == previousState){
            Log.i(TAG, "number: " + incomingNumber + "");
            Toast.makeText(mContext,"Incoming Call: " + incomingNumber + "",Toast.LENGTH_LONG).show();
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                        SmsManager smsManager =     SmsManager.getDefault();
                        smsManager.sendTextMessage(incomingNumber, null, "I'm busy bruh", null, null);
                    TelephonyManager tm = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
                    tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

            }

                   }
            previousState = state;
    }
};}

A: In your code:
you are registering PhoneStateListener inside onReceive(), so whenever your onReceive method invoked it will add one more PhoneStateListener to TelephonyManager. So, you have multiple listeners for the same event over the period.
What you can do is, you need to check if the listener is added before if so just skip that part.


text:
Q: Batch insert with EclipseLink not working I am using EclipseLink-2.6.1 with Amazon RDS database instance. The following code is used to insert new entities into database:
 tx = em.getTransaction();
 tx.begin();
 for (T item : persistCollection) {
     em.merge(item);
 }
 tx.commit();

The object which is being persisted has composite primary key (not a generated one). Locally, queries run super fast, but when inserting into remote DB it is really slow process (~20 times slower). I have tried to implement JDBC batch writing but had no success with it (eclipselink.jdbc.batch-writing and rewriteBatchedStatements=true). When logging queries which are being executed I only see lots of SELECTS and not one INSERT (SELECTS are probably here because objects are detached at first).
My question is how to proceed on this problem? (I would like to have batch writing and then see how the performance changes, but any help is appreciated)
Thank you!
Edit:
When using em.persist(item) loop is finished almost instantly but after tx.commit() there are lots (I guess for every persisted item) queries like :
[EL Fine]: sql: ServerSession(925803196) Connection(60187547) SELECT NAME FROM TICKER WHERE (NAME = ?), bind => [AA]

My model has @ManyToOne relationship with ticker_name. Why are there again so many slow SELECT queries?


text:
Q: How to one hot encode with pandas on a new dataset? I have a training data set that has categorical features on which I use pd.get_dummies to one hot encode. This produces a data set with n features. I then train a classification model on this data set with n features. If I now get some new data with the same categorical features and again perform one hot encoding, the resultant number of features is m < n.
I cannot predict the classes of the new data set if the dimensions don't match with the original training data.
Is there a way to include all of the original n features in the new data set after one hot encoding?
EDIT: I am using sklearn.ensemble.RandomForestClassifier as my classification library.

A: For example ,
You have tradf with column ['A_1','A_2']
With your new df you have column['A'] but only have one category 1 , you can do
pd.get_dummies(df).reindex(columns=tradf.columns,fill_value=0)


text:
Q: Android Gallery Text Only I've looked into the API Demos and they have an example of the gallery where they show just text, the code just uses a Cursor , however I want to use a String array. How can I achieve using it? This is the code for the example in API Demos:
        Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
    startManagingCursor(c);

    SpinnerAdapter adapter = new SimpleCursorAdapter(this,
    // Use a template that displays a text view
            android.R.layout.simple_gallery_item,
            // Give the cursor to the list adatper
            c,
            // Map the NAME column in the people database to...
            new String[] {People.NAME},
            // The "text1" view defined in the XML template
            new int[] { android.R.id.text1 });

A: If you just want to display a static list of String objects, an ArrayAdapter should do:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, new String[] {People.NAME});

However, if you want to be able to add more String objects to the list later, you should use a List.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, new ArrayList<String>());

A: You need to replace the CursorAdapter with an ArrayAdapter.


text:
Q: How to solve variable value in definite integral? I have a definite integral:
$$\int_{-1}^3(a-x)dx = 12$$
I need to find the value of constant $a$ so that equation is true. Here is what I have tried:
First integrate using the exponent function integration formula:
$$\frac12a^2-\frac12x^2+C$$
Then form the equation:
$$f(x)dx = F(b) - F(a) = 12$$
Write the equation:
$$\frac12a^2-\frac123^2-\frac12a^2-\frac12(-1)^2 = 12$$
Multiply both sides by $2$:
$$a^2-3^2-a^2-(-1)^2=24$$
This however, is not true as it would result in $-10=24$ and $a$ would be completely lost. Could I have some advise?

A: Huge thanks to @Stephen Donovan, here are the correct steps for anyone who might run into same problem. $a$ is constant, not variable, so
$$\int(a-x)dx = ax-\frac12x^2 + C$$
Using the rule $f(x)dx = F(b)-F(a)$ we can create equation:
$$(3a-\frac123^2)-(-a-\frac12(-1)^2) = 12$$
Multiply both sides by two and simplify:
$$(6a-3^2)-(-2a-(-1)^2)=24$$
$$8a = 32$$
$$a=4$$


text:
Q: Android HttpUrlConnection doesn't support digest authentication?
*

*I want to use HTTPURLConnection to enable cache which is supported on android based on doc

*But when using  HTTPURLConnection return 401 responseCode .
    String BASIC_AUTH = "Basic "
        + Base64.encodeToString((USER+":"+PASS).getBytes(),
                Base64.NO_WRAP);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

con.setConnectTimeout(CONNECT_TIMEOUT);
con.setReadTimeout(READ_TIMEOUT);
con.setRequestProperty("Authorization", BASIC_AUTH);
// Enable cache
con.setUseCaches(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "*/*");
// add reuqest header
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.d("Response Code : ", responseCode + ""); // return 401

*When using apache DefaultHttpClient work perfect.
    DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
        new AuthScope(null, -1),
        new UsernamePasswordCredentials(USER,PASS));

HttpResponse httpResponse;
HttpEntity httpEntity;
String url = apiURL.getURL();
// request method is GET
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "text/json");
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();

*The question how to set Credentials on HTTPURLConnecion to work like apache DefaultHttpClient.

A: The default mechanism to set the credentials is using Authenticator.setDefault, but it will only work for basic authentication.
HttpUrlConnection on Android does not support digest yet, you therefore have to implement RFC2617 by yourself.
See my answer here for a summary on how to do that.

A: Try "user:pass" without the spaces.


text:
Q: function that works immediately and replaces all the english numbers to arabic numbers I have this function
var map =
[
"&\#1632;","&\#1633;","&\#1634;","&\#1635;","&\#1636;",
"&\#1637;","&\#1638;","&\#1639;","&\#1640;","&\#1641;"
];

function getArabicNumbers(str)
{
    var newStr = "";

    str = String(str);

    for(i=0; i<str.length; i++)
    {
        newStr += map[parseInt(str.charAt(i))];
    }

    return newStr;
}

which is taken from How can I view Arabic/Persian numbers in a HTML page with strict doctype?
This function will only work if you put something between the parenthesis in getArabicNumbers() when you call out for it.
I want to apply this function on the document from its beginning to its end! how can I do that? Is it possible in javascript? do you recommend it?
any other way to replace English numbers to Arabic numbers using javascript (on the full page not on a string)?

A: You need to walk the DOM tree and for each textnode call replace with the getArabicNumbers.
I would change the getArabicNumbers function to a regex probably; all you need to do is match 0-9 and then map it using a callback.
Edit:
Here's a little fiddle I put together for the fun of it and to demonstrate what I'm talking about and it seems to work perfectly although I am a little unsure about the Right-To-Left part...
Edit2:
D'oh... You can even do without the map[] array.


text:
Q: Scroll to top of div when it is not displayed I have a div full of typeahead search results.  When the input that the typeahead is bound to loses focus, I'd like the div that has the typeahead results to be scrolled to the top most position.
I'm using typeahead.js, so I currently have:
$('input[name="customer"]').on('typeahead:closed', function(){
    $('div.tt-dataset-customers').scrollTop(0);
});

The div is never scrolled, however.  Thinking that this was due to the div being hidden, I've also tried:
$('input[name="customer"]').on('typeahead:open', function(){
    $('div.tt-dataset-customers').scrollTop(0);
});

This did not work either.
Is there a way to set a scroll position on a div that isn't being shown?
Fiddle showing what's happening: http://jsfiddle.net/tTdF4/

A: Edit v3
So I've added a console.log on this and it never fired.
$('input[name="customer"]').on('typeahead:closed', function(){
    console.log('test');
});

So instead of splitting typeahead() from on(), I've used jQuery chain and now it is  triggering typeahead:closed. Don't ask me why it wasn't triggering, still didn't figured out :(.
Anyways, this will work (tested on chrome v29) when you type a, scroll down, click outside then click back on the input, the list will be back up.
$('input[name="customers"]').typeahead({
    local: ['a','ab','ac','ad','ae','af',
            'ag','ah','ai','aj','ak','al',
            'am','an','ao','ap','aq','ar',
            'as','at','au','av','aw','ax',
            'ay','az'
    ],
    limit: 20,
    name: 'customers',
    rateLimitWait: 100,
    ttl: 300
}).on('typeahead:closed keypress', function(){
    console.log('test');
    $('div.tt-dataset-customers').animate({
        scrollTop: 0
    }, 900);
});

Updated fiddle
p.s.: At least on fiddle, jquery 2.X and typeahead gives errors on both scritps on IE9 (see console), if you use 1.9 (edge) then it will work.
V3: Added keypress to the listened events so it will try scroll up everytime someone type something (covers typing a, backspacing and typing b for e.g.).


text:
Q: Flutter: Is it possible to have multiple CameraControllers? We are developing an app to analyse an image stream from the camera plugin
controller.startImageStream((CameraImage img)
We want to record at the same time using controller.startRecording()
The stream would stop streaming if a second controller is made.
Is there a way to record while having an open image stream?


text:
Q: $compile()'d anchor states cause full browser reload not state change in angularjs How do I get a native angularjs state change for an anchor link that has been $compile()'d?
Updates: 2018-06-18 - Still hitting this problem. Been searching like crazy trying different things and still nothing; 2018-05-28 - I'm still having this issue and don't really have any leads. I've tried many variations and the problem of dynamically linking text with native angularjs state changes remains.
I have some untrusted text which I pass through a service that links #hashtags and @mentiontags. I use $sce.trustAsHtml() and I assign the linkified text back to a $scope.text variable which I use in the view. It works, I can see and click on the link, but instead of a state change I'm getting a full browser url load.
I've checked the state change when done normally through a view and it works.
So, for example:

*

*I have some untrusted text: Hey, @user, you'll love this!

*I pass it through the linking function and get this: Hey, @user, you'll love this!"

*I $compile() that to get states linked up and when inspected in the DOM, it looks like this: Hey, @user, you'll love this!
But when I click the link it's not an angularjs state change, it's a full browser url reload.
Any ideas?
Thanks,

A: Not sure what your problem is. I would expect that, if you click a link, you get out of your page. A trick could be to open link in new tab with target:
@user

However, if it comes from $compile, here is a sample code I use that works:
link: function ($scope, $element, $attrs) {
    $scope.x = "x variable";
    var html = 'your html here like in a template: $scope.x = {{x}}';
    var e = $compile(html)($scope);
    $element.replaceWith(e);
}

Hope it helps!

A: AngularJS ng-bind-html="html" was not processing embedded directives in the "html" (although somehow it was generating accurate hrefs from ui-sefs...).
Based on this question's answer I was able to get the embedded directives to execute.
The solution was to provide a "compile" directive which, while acting like ng-bind-html, would actually fully compile and process directives. More details are in the linked question.


text:
Q: Git: Strategy for Dealing with Merge Conflicts? I use a private repository on Bitbucket as a convenient way of syncing a project (C source code) across several machines I work on; I am the only developer working on the project.
When working on a remote machine (I ssh to it) and trying to git pull I get the following error message:
"You are in the middle of a conflicted merge."
It exits without doing the fast forward merge.
How do I go about resolving this? How do I force a merge on this machine?
I am not averse to trying to reset to an earlier state.

A: Apparently you are in the middle of a prior merge attempt that had some conflicts.  Your first step would be to understand what happened and where you are.  Do
git status

This will show you what files are conflicted.  Once you understand what happened you can decide to resolve the conflicts (see the link provided by @rcdmk).  If, instead, you decide you just want to blow away the prior merge, then you can do:
git merge --abort

But you'll want to be very careful with this as stuff will disappear.  You will be okay if the remote has everything you want; so follow up with:
git pull

A: When you face merge conflicts, there's a lot of options to follow, but you can consult the Git manual on this topic for a help. Also, a similar question has been asked here:
How to resolve merge conflicts in Git?


text:
Q: Print description in XCode shows the correct value, using the variable shows wrong value I'm working on a JSON response from a server, and in the response data, among other things, should be a "credits" property, which is an int, which should have the value of 2000. However, if I try to use this property, I get a value like 180988576. But, if I "print description" of the property from the debugger, it says:
Printing description of playerData->_credits:
2000

How do I access this value?

A: What you have to do is , When you are fetching the value from JSON
use like this :
[[JSON ObjectForKey:@"Key"]integerValue];
It will give you the correct result. Try it once. You can assign that value to an integer variable.


text:
Q: How do we just have $\log$ solution? Mathematica solves this but I want the solution just as Ln[..]?!!
DSolve[y'[t] == 3/2 a*y[t] ((y[t] + b)^2 - f), y[t], t]

thanks

A: This is a separable ODE of the first order. Let us make one step by hand and obtain
t == Integrate[1/(3/2 a*y[t] ((y[t] + b)^2 - f)) /. y[t] -> z, z] /. z -> y[t]

t+ C[1]==(2 (-((2 b ArcTanh[(b+y[t])/Sqrt[f]])/Sqrt[f])-2 Log[y[t]]+Log[-f+(b+y[t])^2]))/(3 a (-2 b^2+2 f))

instead of

InverseFunction[(-((2 b ArcTanh[(b + #1)/Sqrt[f]])/Sqrt[f]) -  2 Log[#1] + Log[b^2 - f + 2 b #1 + #1^2])/(-2 b^2 + 2 f) &][( 3 a t)/2 + C[1]]

produced by
DSolve[y'[t] == 3/2 a*y[t] ((y[t] + b)^2 - f), y[t], t]

Hope you feel the difference.
PS.
t + C[1] == (2 (-((2 b ArcTanh[(b + y[t])/Sqrt[f]])/Sqrt[f]) -
   2 Log[y[t]] + Log[-f + (b + y[t])^2]))/(3 a (-2 b^2 +
   2 f)) // TrigToExp

t + C[1] == (1/(3 a (-2 b^2 + 2 f))) 2 (-2 Log[y[t]] - ( b (-Log[1 - (b + y[t])/Sqrt[f]] + Log[1 + (b + y[t])/Sqrt[f]]))/ Sqrt[f] + Log[-f + (b + y[t])^2])

gets rid of ArcTanh.


text:
Q: Home/Index not found. Can't I use a constraint? I have the classic default ASP.NET MVC route:
  System.Web.Routing.RouteTable.Routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  );

Because I would like to have another HomeController inside an area I added the following:
  System.Web.Routing.RouteTable.Routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional },
      typeof(MVCSite.Controllers.HomeController).Assembly
  );

So that this route is only for the root home controller.
But when I start the site with this I get a 404 error.
Why is that? Can't I specify this constraint?
Thank You!

A: I was able to solve this using:
RouteTable.Routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  new String[] { typeof(HomeController).Namespace
});

Thank You,
Miguel


text:
Q: How can I propagate mousemove events from inside a bootstrap tooltip to an svg element at the same position I have an svg element containing a circle element. I've attached a bootstrap tooltip to my circle element using body as its container so that the tooltip displays properly. The SVG has a mousemove event which captures all mouse movements in its bounding rect.
I would like the SVG to still receive these mousemove events when the mouse pointer s inside a tooltip displayed over the SVG. However my tooltip is not propogating these events to the SVG, and when the mouse is inside the tooltip, a 'mouseleave' event is being sent to the SVG which is not what I want.
I tried alternatively attaching the mousemove event to $(document) like
$(document).on('mousemove', $('#hover-circle'), function() {...} );

but this still doesn't receive mousemove events when pointer is inside tooltip.
At this point, I'm thinking of capturing mousemove events inside the tooltip and manually
passing them on to the SVG, however I'd rather not do this.
var svg = d3.select(panel[0]).append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .on("mousemove", function() {
       console.log('test');
    });

const hoverCircle = svg.append("g")
    .append("circle")
    .attr("id", "hover-circle")
    .attr("r", 3)
    .attr("cx", xScale(closestIndex))
    .attr("cy", yScale(dataset[closestIndex].y))
    .attr("title", dataset[closestIndex].evalStr)
    .tooltip({
         container: 'body',
         trigger: 'manual'
      })
    .tooltip('show');

A: I've come up with a possible solution to this now using
$('.tooltip').css('pointer-events', 'none');
This causes mouse events to pass through the absolute positioned tooltip to an underlying element. Seems to be compatible with most browsers these days.


text:
Q: Split One Column to multi column in TSQL I need solve my problem in TSQL
Current Table
TRX      DOC      ITEM      DOCTYPE      QTY
--------------------------------------------
123      ASM1     001       1            100
124      ASM2     002       1             10
234      ADJ1     002       2            -30
456      SAL1     001       3            -20
457      SAL2     002       3            -10
789      PRE1     002       4             10
910      ADJ2     001       2             20

How to split column QTY to sum(QTY) AS QTYIN and QTYOUT like this
ITEM    QTYIN    QTYOUT   TOTQTY
---------------------------------
 001      120       -10     110
 002       20       -50     -30

Thanks for help, I need solution.

A: Use a GROUP BY clause to combine results by Item, then SUM with a CASE statement to total over specific criteria (DEMO):
select
  item,
  sum(case when qty > 0 then qty end) as qtyin,
  sum(case when qty < 0 then qty end) as qtyout,
  sum(qty) as totqty
from
  Table1
group by
  Item

Sample Output (I assume the differences are just typos?):
| ITEM | QTYIN | QTYOUT | TOTQTY |
----------------------------------
|    1 |   120 |    -20 |    100 |
|    2 |    20 |    -40 |    -20 |


text:
Q: Multithreading using boost: Compiler error I am trying to capsulate a thread as it is shown here:
http://antonym.org/2009/05/threading-with-boost---part-i-creating-threads.html
But somehow I can't even compile my program.. This:
/**
 *
 */
void AcceptConnectionThread::start(int param)
{
  m_thread = boost::thread(&AcceptConnectionThread::AcceptConnectionThreadRun, this, 0);
}

/**
 *
 */
int AcceptConnectionThread::AcceptConnectionThreadRun()
{
  return 0;
}

just gives me this:
Description Resource    Path    Location    Type   required from `boost::_bi::bind_t<R, F, L>::result_type boost::_bi::bind_t<R, F, L>::operator()() [with R = void; F = int (*)(); L = boost::_bi::list2<boost::_bi::value<AcceptConnectionThread*>, boost::_bi::value<int> >; boost::_bi::bind_t<R, F, L>::result_type = void]'   ServerNetwork       line 20, external location: /usr/include/boost/bind/bind_template.hpp   C/C++ Problem
Description Resource    Path    Location    Type   required from 'void boost::detail::thread_data<F>::run() [with F = boost::_bi::bind_t<void, int (*)(), boost::_bi::list2<boost::_bi::value<AcceptConnectionThread*>, boost::_bi::value<int> > >]'    ServerNetwork       line 62, external location: /usr/include/boost/thread/detail/thread.hpp C/C++ Problem
Description Resource    Path    Location    Type too many arguments to function ServerNetwork       line 313, external location: /usr/include/boost/bind/bind.hpp   C/C++ Problem

This is the template-constructor that is used:
template <class F,class A1,class A2>
thread(F f,A1 a1,A2 a2):
    thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2)))
{
    start_thread();
}

I really do not have any idea what the problem is..
EDIT:
Anyway, it works with this.. but this way I can't pass any parameter..
/**
 *
 */
void AcceptConnectionThread::start(int param)
{
  m_thread = boost::thread(&AcceptConnectionThread::AcceptConnectionThreadRun);
}

A: use boost::bind

    /**
     *
     */
    void AcceptConnectionThread::start(int param)
    {
      int para_to_pass = 0;
      m_thread = boost::thread( boost::bind(&AcceptConnectionThread::AcceptConnectionThreadRun, this, para_to_pass));
    }

    /**
     *
     */
    int AcceptConnectionThread::AcceptConnectionThreadRun(int para)
    {
      // use para
      return 0;
    }


text:
Q: How to share data or computations among training samples I need to train a classifier, that should be based on 3 things: features of an object itself, some kind of context image representing its state relative to other objects, and a sequence of images representing even more context, but somewhat globally. The number of objects varies between images.
As for the neural network:
- the first input has a shape of (batch_size, n), where n is the number of objects features (n~15);
- the second input has roughly a shape of (batch_size, image_size, image_size, n), where image_size is the size of an image (image_size ~ 15);
- the shape of the third input, as you might guess, is (batch_size, seq_len, image_size, image_size, n), where seq_len is sequence length (seq_len ~ 10).
When the number of training samples is relatively small, this is feasible. But when the number exceeds 100k examples, it already takes 12GB of memory. And that's too much since I need to feed even more. Things are going to be even worse when I will need to train something similar, but now for each pair of objects on the image.
But the thing is, that most of the data does not change between samples. If some image has 15 objects, then only the first and the second inputs will be different for those 15 objects, while the biggest one (the third) will remain the same. The computations needed for all the inputs are the same.
Despite my specific problem, it raises the general question if I can feed the third input only as many times as needed and perform the same computations for different samples?
P.S:
1) I would highly appreciate a better question formulation: I don't know if there is something out there and if that something has a name;
2) I do know about the existence of tf.data. But I can't seem to find any examples answering my question.


text:
Q: sdk grails and lazybones init fatal error I can't use grail and lazybones installed via sdkman.
I have got fatal errors.
OS: Ubuntu 16.04
$ java -version
openjdk version "9-internal"
OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)

$ sdk version
SDKMAN 5.7.2+323
$ sdk install grails
$ grails -version
| Grails Version: 3.3.8
| Groovy Version: 2.4.15
| JVM Version: 9-internal

$ sdk install lazybones
$ lazybones -version
Lazybones version 0.8.3
$ grails create-app --stacktrace helloworld
Resolving dependencies..
| Error Error occurred running Grails CLI: Received fatal alert: handshake_failure (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:436)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:643)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:137)
    at org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:287)
    at org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:243)
    at org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:59)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:447)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:350)
    at org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:581)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:249)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:223)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:320)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:217)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor(DefaultDependencyCollector.java:535)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult(DefaultDependencyCollector.java:519)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:409)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:254)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:341)
    at org.springframework.boot.cli.compiler.grape.AetherGrapeEngine.resolve(AetherGrapeEngine.java:318)
    at org.springframework.boot.cli.compiler.grape.AetherGrapeEngine.resolve(AetherGrapeEngine.java:300)
    at org.springframework.boot.cli.compiler.grape.AetherGrapeEngine.resolve(AetherGrapeEngine.java:292)
    at org.grails.cli.boot.GrailsDependencyVersions.<init>(GrailsDependencyVersions.groovy:54)
    at org.grails.cli.boot.GrailsDependencyVersions.<init>(GrailsDependencyVersions.groovy:50)
    at org.grails.cli.profile.repository.MavenProfileRepository.<init>(MavenProfileRepository.groovy:53)
    at org.grails.cli.GrailsCli.createMavenProfileRepository(GrailsCli.groovy:334)
    at org.grails.cli.GrailsCli.execute(GrailsCli.groovy:235)
    at org.grails.cli.GrailsCli.main(GrailsCli.groovy:159)
| Error Error occurred running Grails CLI: Received fatal alert: handshake_failure

$ lazybones list
Can't connect to pledbrook/lazybones-templates: Unable to make member of class sun.net.www.protocol.https.HttpsURLConnectionImpl accessible:  module java.base does not export sun.net.www.protocol.https to unnamed module @75f65e45

A: To me that looks like an SSL handshake error when grails is doing some of its initialisation work for create app. It might be attempting to pull down some required jar files etc.
What does sdk list grails show?
What does which grails and which javareturn?
I've not used jdk 9 heaps so might be worthwhile investigating changing that also. I think you'll find switching to jdk8 will have better results. Each jdk comes with a list of standard root certificate authorities it trusts.
Maybe with the recent security issues like the one surrounding the Symantec CAs jdk9 might have removed these but the server grails is connecting to is still using one perhaps.
Edit: I think you may also have been using an internal development build version of Java 9 jdk. as you reported to using build 9-internal+0-2016-04-14-195246.buildd
Try using jdk 8 or installing a newer version of Java 9.


text:
Q: unkown command '<' when using sed command I'm trying to update xml file via bash script.
I saw some answers which advise to use sed command.
I'm trying to do so, but getting errors, and can't find the right way.
I have the following xml file:
<System>
   <HW value="true" />
   <Tm4 value="true" />
</System>

I want to replace the value of HW from true to false:
<HW value="true" />   →   <HW value="false" />
I wrote the following script:
sed -i '<HW value="false" \/>' / <HW value="true" \/> myXmlFile.xml

But getting the following error:
syntax error near unexpected token '<'

What am I doing wrong and what is the right code line?

A: You better choose other character than / to edit XML with sed, to make your code readable, eg.
sed -i 's|<HW value="false" />|<HW value="true" />|g' myXmlFile.xml


text:
Q: NSNumberFormatter with number style NSNumberFormatterCurrencyStyle trouble with commas I'm trying to do things right with input expenses on some items. So, when working on a device using a locale that uses comma separated decimals (the decimal pad automatically sets comma ',' instead of dot '.' for the user to input) I store the value using core data in a double variable converting the text this way:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:2];
NSNumber * gasto = [f numberFromString:(((UITextField*) [cell viewWithTag:11]).text)];
destino.nuevaTrans.gasto = [gasto doubleValue];
//destino.nuevaTrans is the managed object, nothing weird there, just storing the decimal value

But when taking the value out of the stored objects and showing them in a table view I'm losing the decimals because of the comma separated locale settings (?). Doing it this way:
etiq = (UILabel*) [cell.contentView viewWithTag:12];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
etiq.text = [numberFormatter stringFromNumber:@(trans.gasto)];

//debugging console output:
//remmember, trans.gasto is only a double
NSLog(@"a: %f, b: %@", trans.gasto ,[numberFormatter stringFromNumber:@(trans.gasto)]);

The output on the simulator that is using dot '.' locale settings works fine, but when deploying on the device that is using comma ',' settings the NSNumberFormatter doesn't seem to translate it correctly to currency style.
//output on the simulator:
2014-09-07 15:00:47.561 iSpend[3930:60b] a: 2.990000, b: $2.99

//output on the device:
2014-09-07 15:02:40.005 iSpend[1389:60b] a: 2.170000, b: ₡2

So, I could try and hack this thing out... But I'm looking for a better programming practice here. Every suggestion is appreciated! Thanks!

A: Each Locale determines if it shows cents or just Krona. So, if you want to force it to show digits after the comma, add the line:
[numberFormatter setMinimumFractionDigits:2];

to get two digits after comma.
But the example you show has correct output.

A: u can try to set separator clearly: [formatter setDecimalSeparator:@"."];


text:
Q: sim800 and Codeigniter CSRF token problem hi Sorry for my weak English. I'm trying to receive the JSON data from Sim800 on my Server using Codeigniter. when in config.php file i set the $config['csrf_protection'] = TRUE; the Server Response 403 error and when it's false Server Response 200 and everything is OK.what can i do for this problem? for now in config.php i add this: $config['csrf_exclude_uris'] = array('customer/query');,Is there another way?

in my client side Sim800 module I'm using this commands.
AT+SAPBR=3,1,"CONTYPE","GPRS"
AT+SAPBR=3,1,"APN","mtnirancell"
AT+SAPBR=1,1
AT+SAPBR=2,1
AT+HTTPINIT
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","http://www.mysiteaddress.ir/customer/query"
AT+HTTPPARA="CONTENT","application/json"
AT+HTTPDATA=20,10000 //data is 20 Bytes,maximum latency time is 10000 ms.
// Wait a few moments to Receive "DOWNLOAD" from sim800c module
{"data":"my sensor value"} // The data I want to send

AT+HTTPACTION=1 // send data with POST method

after this commands module response
OK

+HTTPACTION: 1,403,86 // 403 error

and for PHP server I'm using this codes:
$request_body="";
$request_body = file_get_contents('php://input');
$record = urldecode($request_body);
$record = json_decode($request_body,true);


text:
Q: Analysis of microbial community data collected from iPad swabs We have taken a number of swabs (~200) from iPads used in our clinic, and after the first half we've introduced an intervention to disinfect all iPads after every use (in addition to the standard hygiene measures). Besides doing culture, we've sequenced DNA to obtain information about what different bacterial species were contained in every sample. The sequencing data now consists of ~120 species, given as percentage contained in each sample (eg. sample5 contains species1 40%, species7 30% and species18 10%).
As an additional analysis I would now like to compare the microbiome (i.e. abundance of species from each sample) before the intervention with that after the intervention, and have thought of creating a (dis)similarity matrix of all species and using multidimensional scaling before and after intervention.
Is this an adequate way to do it? Are there other/better methods?
As I've never done this, and the resources on the web seem a bit scarce, do you have any pointers to recommended literature or tutorials, especially for Stata 13?

A: That sounds like what people do these days. There are tons of ecological similarity measure that you can use in order to construct your similariy metrics. you can use spectral clustering which are special case of multidimensional scaling for similarit matrices. You can use pair-wise test to see level of significants; I would say the best source you can start with is the phyloseq package;


text:
Q: Python watchdog on network shares right issues Im using python 2.7 on Windows 7 Enterprise SP1 with watchdog to watch some network shares for file changes. I have to networkshares on the same physical (assumed Linux) host that are connected to two different subfolders. So let's say I connected to networkshare
Y: = //host/a

while the other networkshare is
X: = //host/b

I'm running a simple
watchmedo log --recursive

on both Y: and X:.In the first case I see a lot of file IO events being logged to console, in the second there is plain nothing. There should be no difference on the filesystem or anything environment related.
Update: I even ruled out the user access rights on the network share being the issue by connecting both drives under the same windows account.


text:
Q: Bootstrap - Maintaining  collapse state between refresh A bit of a js/jquery novice - I'm using Bootstrap and data-toggle + collapse classes to show/hide divs.  I've been scouring the 'net trying to find something that will maintain the state of all divs, whether identified by a unique ID or a CLASS, between page refreshes.  I've seen discussions on cookies and local storage, I don't think I care which method is used (although I've had errors with $.cookie is not a function, so maybe local storage is better?).
The issue is most examples deal with maintaining accordion states, which I don't think exactly apply here.  I've tried modifying various code examples but they just don't quite seem to work.
Here is an example of my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

     Top 5 Expiring Tasks

          Name
          End Date

           Take Out The Trash
          Yesterday

     Top 5 Urgent Tasks

          Name
          Priority

           Save the Whales
          Critical

As you can see, there's a link or a button or something that toggles showing/hiding a div.
Same thing on JSFiddle: http://jsfiddle.net/w8psgvaa/2/
I found this code example;
 $('.collapse').on('hidden', function() {
       // store this.id
 }).on('shown', function() {
       // delete this.id
 });

 $(document).ready(function(){
     $(".collapse").collapse().each(function(){
         if( isStored( this.id ) ) {
             $( this ).collapse( 'hide' );
         }
     });
 });

But unfortunately it's incomplete. and some divs start out collapsed (as in my example).  Any help is appreciated!

A: You are looking in  the right direction.
My solution would be the following.
Use LocalStorage, available in modern browsers.

*

*When a div is collapsed: remove the div's ID from the storage

*When a div is opened: add the div's ID from the storage.

This is as easy as
var shown = []

// On collapse
shown.remove($(this).attr('id'));
localStorage.setItem('shown', shown);

// On open
shown.push($(this).attr('id'));
localStorage.setItem('shown', shown);

// On page load
var shown = localStorage.getItem('shown');
for (var s in shown) {
    $('#' + s).show(); // Or whatever API you use to un-collapse the div
}

More information: http://diveintohtml5.info/storage.html

A: Here is a working example, using Bootstrap panel-collapse and LocalStorage, similar to Hidde's answer. I'm using JSON "stringify" and "parse" functions to store my ids in localStorage, which stores everything as strings.
I also use Bootstrap's collapse events.
// On document ready

var shownOnRefresh = [];
localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));

$('#myParentElement').on('shown.bs.collapse', '.panel-collapse', function() {
        shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
        if ($.inArray($(this).attr('id'), shownOnRefresh) == -1) {
            shownOnRefresh.push($(this).attr('id'));
        };
        localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));
});

$('#myParentElement').on('hidden.bs.collapse', '.panel-collapse', function() {
        shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
        shownOnRefresh.splice( $.inArray($(this).attr('id'), shownOnRefresh), 1 );//remove item from array
        localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));
});

// On page refresh
var shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
for (var i in shownOnRefresh ) {
    $('#' + shownOnRefresh [i]).addClass('in');
}

I'm a jquery novice, so this code can certainly be optimized, but it does the job.


text:
Q: Probability of a uniform distrubated stochastic variable larger than another So let's say I have two independent random variables $X \sim U(0,1)$ and $Y \sim U(0,1)$. I want to find the probability $P(Y>2X)$
For a uniformly distributed random variable $P(X<a) = F(x) = \frac{x-a}{b-a}$
However, I'm not sure how to calculate the probability when $a$ is a random variable.

A: For independent $X$ and $Y$ we have
$$
P((X,Y)\in A)=\int_\mathbb{R} P((x,Y)\in A)\, P_X(\mathrm dx)=\int_\mathbb{R} P((X,y)\in A)\, P_Y(\mathrm dy)
$$
for any (measurable) $A\subseteq \mathbb{R}$. Use this with $A=\{(x,y)\in\mathbb{R}^2\mid y>2x\}$.
The above immediately yields
$$
\begin{align}
P(X<\tfrac12 Y)&=\int_\mathbb{R} P(X<\tfrac12y) f_Y(y)\,\mathrm dy\\
&=\int_0^1 F_X(\tfrac12 y)\,\mathrm dy=\frac14
\end{align}
$$
since $F_X(x)=x$ for $x\in [0,1]$.

A: Consider the RV $Z=Y-2X$ (which takes values from $[-2,1]$). The probability that $Z<0$ is the probability that $2X> 1$ (probability $1/2$) plus the probability that $2X\le 1$ (i.e., $X\le 1/2$ - with probability $1/2$) and $Y\le 2X$, which is the probability that one random uniform $[0,1]$ distributed RV is smaller or equal than another. The latter event has probability $1/2$ since $P(X>Y)+P(X<Y)=1$ and then use symmetry.
So, $P(Z<0)=\frac{1}{2}+\frac{1}{2}\frac{1}{2}=\frac{3}{4}$, so
$$P(Y-2X\ge 0)=P(Z\ge 0)=1-\frac{3}{4}=\frac{1}{4}.$$

A: Draw a pair of axes, and the $1\times 1$ square on which the joint density function "lives."
Draw the line $y=2x$.
We want the probability that the pair $(X,Y)$ ends up (in the square and) above the line.
This is the area of a certain right triangle, divided by the area of the square, which conveniently happens to be $1$.
Remark: If the joint density function happened to be zero outside the square, but not constant in the square, the procedure is roughly similar. But instead of finding the area of the triangle, you would integrate the joint density function over the triangle.


text:
Q: Android client communicating with jboss server My android client makes a URLconnection to a servlet deployed on jboss. But when i run the client in emulator there seems to be no connection being established. My client code:
URL url = new URL("http://192.168.56.1:8080/hello");
              URLConnection connection = url.openConnection();
              connection.setDoOutput(true);
              ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());
                String s=new String("success");
                out.writeObject(s);
                out.flush();
                out.close();

There is no response in jboss. 192.168.56.1 is the ip address of my machine. Since 'localhost' will refer to the emulator itself, I have used 192.168.56.1.(ipcofig)
What is the problem.
This is after I made the suggested changes(i.e gave the internet permission in android manifest.xml and changed the url to 'http://10.0.2.2:8080/hello' to refer to my machine).
But i still get this exception when I run my application(Client):
ActivityManager: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.Client/.ClientActivity } from null (pid=-1, uid=-1) requires android.permission.INTERNET

Now it is working. I added the in internet permission to the manifest tag. Earlier I had added it inside the application tag.
With reference to my original question, still there is no response from the jboss server evene after making all the suggested changes. There seems to be no connection being made between the emulator and the jboss server.

A: So assuming your JBoss server is running on the same PC as your emulator, here
are a few things you can check:
First off, make sure you have the Internet permission set in your
   AndroidManifest.xml as
   Thinksteep
   pointed out:
<uses-permission android:name="android.permission.INTERNET" />

Secondly, try changing the IP address in:
URL url = new URL("http://192.168.56.1:8080/hello");

To:
URL url = new URL("http://10.0.2.2:8080/hello");

Details here. Essentially what this is doing is that assuming you have your JBoss serving off localhost on your development machine (i.e. serving off 127.0.0.1), your emulator should be able to connect via this special IP address.


text:
Q: error when compile opencv in qt applying tbb I Have the following issue when compiling opencv project in qt applying tbb
dyld: Library not loaded: libtbb.dylib
Referenced from: /usr/local/lib/libopencv_core.2.4.dylib
Reason: image not found
The program has unexpectedly finished.

Can any friend tell me how to solve this problem?

A: Oh, I suddenly solved this problem by copy the libtbb.dylib to /usr/local/lib/ folder.
Thank

A: The problem is when you are running your application it can't find the libraries to load. You need to set the DYLD_LIBRARY_PATH environment variable to point to the directory containing this library in your application scheme.
Product > Edit Scheme > Environment Variables


text:
Q: Split string in List of string I have the following code where i'm trying to split a string and add it to my List of String. But i'm having trouble doing it like this:
List<string> filteredProviders = new List<string>();

foreach (Door2MoreLeadModel d2m in lstDoor2MoreLeadModel)
{
    if(!string.IsNullOrEmpty(d2m.FilteredProviders))
    {
        filteredProviders.Add(d2m.FilteredProviders.Split(',')).ToList());
    }
}

Getting following error:

The best overloaded method match for
  System.Collections.Generic.List.Add(string)' has some invalid
  arguments

What am I doing wrong?

A: Use AddRange() instead of Add(), Split() returns an array of strings and ToList is a List<T>, but Add() method accepts just string.
filteredProviders.AddRange(d2m.FilteredProviders.Split(',')).ToList());

even without ToList():
filteredProviders.AddRange(d2m.FilteredProviders.Split(',')));

References: List.Add(T) Method, List.AddRange(IEnumerable) Method

A: filteredProviders.Add(d2m.FilteredProviders.Split(',')[0]).ToList());

or
filteredProviders.Add(d2m.FilteredProviders.Split(',')[1]).ToList());

By split() you create array of strings and you have to choose which to use.
Or use all of them
filteredProviders.AddRange(d2m.FilteredProviders.Split(',')).ToList());


text:
Q: Control Amplifier from Computer via RS232 I got a second hand Rotel RSX-1056 amplifier that I would like to control from my computer (because I don't have the remote).
The amplifier has a serial port (RS232) and on the web I was able to find a specification for the communications:
http://www.rotel.com/sites/default/files/product/rs232/RSX1056%20Protocol.pdf
My computer is a hackintosh running OS X 10.11.3.
So I bought an FTDI serial (RJ45) to USB cable and tried to send some messages to the amp. I wasn't sure how to change the buad speed etc on OS X because stty on OS X seems to be problematic in this regard and sets it back to the value it was upon quitting. Regardless of that I tried running something like (the code to bring the volume up):
echo -ne '\xFE\x03\xC5\x10\x0B\xE3' > /dev/tty.usb-serial
and it hangs.
I replace the tty with cu and it doesn't hang, but nothing happens.
I tried using CoolTerm for Mac OS X;  I was able to get some data sent to the computer from the amp when changing the volume knob physically on the amp, but when I tried to send an hex code from computer to amp via CoolTerm, again, nothing happens.
Here are some screen shots from CoolTerm:

At that point I started thinking that maybe the FTDI Mac OS X drivers are faulty. So I tried to use a Windows VM with the FTDI and that also didn't help (getting data when pressing physical buttons on amp, and nothing happens when sending data to amp).
I also tried to use a VM with Ubuntu, in which case stty does work, but again, hexdump -C shows data sent from amp, but echo doesn't do anything or hangs.
At this point I started suspecting that the chip I have is faulty, so I purchased a PL2303 USB to serial adaptor. I installed the Prolific drivers, and again, the whole same thing happens: can receive data, and when sending nothing happens.
If anyone has any advice about this I would be most grateful, as right now I have no way to change the volume on the amp other than getting up and turning the knob.


text:
Q: JQuery and Autocomplete Using a List (Python/Flask) This has probably been asked before, but after searching for awhile I'm still a bit confused. I'm trying to make a flask app but I'm not too familiar with JQuery itself, but I would like to create an autocomplete widget in my html. However, instead of querying a database I'd like to just use a static list and a regex to get results. I used this as reference.
What I did was:
@app.route('/autocomplete', methods=['GET'])
def autocomplete():
    search = request.args.get('q')
    #query = db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%'))
    #results = [mv[0] for mv in query.all()]
    results = ['Beer', 'Wine', 'Soda', 'Juice', 'Water']
    return jsonify(matching_results=results)

while keeping the rest of the code:
<head>
<link href="//code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

<script type="text/javascript">
$(function() {
    $("#autocomplete").autocomplete({
        source:function(request, response) {
            $.getJSON("{{url_for('autocomplete')}}",{
                q: request.term, // in flask, "q" will be the argument to look for using request.args
            }, function(data) {
                response(data.matching_results); // matching_results from jsonify
            });
        },
        minLength: 2,
        select: function(event, ui) {
            console.log(ui.item.value); // not in your question, but might help later
        }
    });
})

</script>
</head>

<body>
    <div>
        <input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>
    </div>
</body>

I haven't implemented a regex but I assumed if I typed anything with at least 2 characters I would get a dropdown of the list I wrote above. However, I get nothing. Any ideas on how I can get this autocomplete to work?


text:
Q: How to properly reward player with Admob in Unity?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using UnityEngine.UI;

public class admobVideo : MonoBehaviour {

 RewardBasedVideoAd rewardBasedVideo;

 static InterstitialAd interstitial;

 string VideoID = "ca-app-pub-6032262586397129~2821965113";
 string adUnitId = "ca-app-pub-6032262586397129/5003220953";

 public static admobVideo Instance;
 void Start ()
 {
  Instance = this;
  DontDestroyOnLoad(gameObject);
  RequestRewardBasedVideo();
  RequestInterstitial();
 }

 public void RequestRewardBasedVideo()
 {
  rewardBasedVideo = RewardBasedVideoAd.Instance;
  rewardBasedVideo.LoadAd(new AdRequest.Builder().Build(), adUnitId);
 }

 public void RequestInterstitial()
 {
  interstitial = new InterstitialAd(VideoID);
  interstitial.LoadAd(new AdRequest.Builder().Build());
 }
 public void ShowAd()
 {
  if(rewardBasedVideo.IsLoaded())
  {
   rewardBasedVideo.Show();
   rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
  }
 }
 public static void ShowInter()
 {
  showInterstitial(interstitial);
 }

 private void showAdd(RewardBasedVideoAd r)
 {
  if (r.IsLoaded())
  {
   //Subscribe to Ad event
   r.Show();
   r.OnAdRewarded += HandleRewardBasedVideoRewarded;
  }
 }

 public void HandleRewardBasedVideoRewarded(object sender, Reward args)
 {

  PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + 5);
  GameObject.FindGameObjectWithTag("Coins").GetComponent<Text>().text = PlayerPrefs.GetInt("coins").ToString();
  GameObject.FindGameObjectWithTag("Double").GetComponent<Button>().interactable = false;

  Debug.Log("Pref: " + PlayerPrefs.GetInt("coins"));
 }

 static void showInterstitial(InterstitialAd i)
 {
  if (i.IsLoaded())
  {
   i.Show();
  }
 }
}

I am rewarding players with 5 coins , But when I click button nothing appears ,  I have tried to change code in many ways but no positive result.
when i click in the button in unity the console show me "Dummy is loaded" and "Dummy showrewardedbasedvideoad"
Method that is called upon button click is ShowAd(). Please Help

A: *

*Please check by adding debug in HandleRewardBasedVideoRewarded  method to check if it's called.

*Also check you have added listener for that as you have not mentioned this in your code mentioned above.
rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;

*You have not initialised mobileAds with your app id:
MobileAds.Initialize();


text:
Q: Create a function that checks whether an array has two opposite elements or not for less than n^2 complexity. (C++) Create a function that checks whether an array has two opposite elements or not for less than n^2 complexity. Let's work with numbers.
Obviously the easiest way would be:
bool opposite(int* arr, int n) // n - array length
{
 for(int i = 0; i < n; ++i)
  {
    for(int j = 0; j < n; ++j)
     {
       if(arr[i] == - arr[j])
          return true;
     }
  }

  return false;
}

I would like to ask if any of you guys can think of an algorithm that has a complexity less than n^2.
My first idea was the following:
1) sort array ( algorithm with worst case complexity: n.log(n) )
2) create two new arrays, filled with negative and positive numbers from the original array
( so far we've got -> n.log(n) + n + n = n.log(n))
3) ... compare somehow the two new arrays to determine if they have opposite numbers
I'm not pretty sure my ideas are correct, but I'm opened to suggestions.

A: An important alternative solution is as follows. Sort the array. Create two pointers, one initially pointing to the front (smallest), one initially pointing to the back (largest). If the sum of the two pointed-to elements is zero, you're done. If it is larger than zero, then decrement the back pointer. If it is smaller than zero, then increment the front pointer. Continue until the two pointers meet.
This solution is often the one people are looking for; often they'll explicitly rule out hash tables and trees by saying you only have O(1) extra space.

A: I would use an std::unordered_set and check to see if the opposite of the number already exist in the set.  if not insert it into the set and check the next element.
std::vector<int> foo = {-10,12,13,14,10,-20,5,6,7,20,30,1,2,3,4,9,-30};
std::unordered_set<int> res;
for (auto e : foo)
{
    if(res.count(-e) > 0)
        std::cout << -e << " already exist\n";
    else
        res.insert(e);
}

Output:
opposite of 10 alrready exist
opposite of 20 alrready exist
opposite of -30 alrready exist

Live Example

A: Let's see that you can simply add all of elements to the unordered_set and when you are adding x check if you are in this set -x. The complexity of this solution is O(n). (as @Hurkyl said, thanks)
UPDATE: Second idea is: Sort the elements and then for all of the elements check (using binary search algorithm) if the opposite element exists.

A: You can do this in O(n log n) with a Red Black tree.
t := empty tree
for each e in A[1..n]
    if (-e) is in t:
        return true
    insert e into t
return false

In C++, you wouldn't implement a Red Black tree for this purpose however. You'd use std::set, because it guarantees O(log n) search and insertion.
std::set<int> s;
for (auto e : A) {
    if (s.count(-e) > 0) {
        return true;
    }
    s.insert(e);
}
return false;

As Hurkyl mentioned, you could do better by just using std::unordered_set, which is a hashtable. This gives you O(1) search and insertion in the average case, but O(n) for both operations in the worst case. The total complexity of the solution in the average case would be O(n).


text:
Q: wp_enqueue_style for specific pages I try to load the css and js files in specific pages. and use this code:
public $pages = array(
    'post', 'post-new', 'profile', 'user-edit',
    'options-general',
);
 public function admin_scripts() {
    $screen = get_current_screen();
    $css_path = 'lib/css/app-admin.css';
    $js_path = 'lib/js/app-admin.js';
    wp_register_style( 'app-admin', APP_URL . $css_path, array(), _ver( $css_path ) );
    wp_register_script( 'app-admin', APP_URL . $js_path, array(), _ver( $js_path ), true );

    if ( in_array( $screen->base, $this->pages ) ) {
        wp_enqueue_style( 'app-admin' );
        wp_enqueue_script( 'app-admin' );
        wp_localize_script( 'app-admin', 'XFAPJS', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce' => wp_create_nonce( 'app_nonce', 'app_nonce' ),
            'base' => $screen->base,
            'blocksEditor' => method_exists( $screen, 'is_block_editor' ) &&      $screen->is_block_editor() ? true : false
        ) );
        wp_add_inline_script( 'app-admin', 'APP.init();' );
    }
}

So the scripts are loaded in  'post', 'post-new', 'profile', 'user-edit', but not in settings page.
I want to load in my plugin settings page also http://wp.local/wp-admin/options-general.php?page=xapp
where is the problem?

A: Follow these steps:

*

*write this line echo $screen->base . 'debug-xyz'; before  if ( in_array( $screen->base, $this->pages ) ) line.

*now go to your page http://wp.local/wp-admin/options-general.php?page=xapp

*View page source(Right-click on the page and click on the View source page or open like this view-source:http://wp.local/wp-admin/options-general.php?page=xapp

*Search for debug-xyz in your page source using Find tool(CTRL +F) then before the debug-xyz you get your page base name.

*copy that base name and add that base name into your public $pages array.

*remove that echo line that we added for getting base value.

*Now check if script is loading on your setting page or not.


text:
Q: Android Camera2, disable auto focus My app uses Camera2 API to take frames as fast as possible. We have a start / stop button to start / stop capturing frames. Focus is either set to auto, or done before capturing. If the focus is done before capturing, then during the capture it must be disabled.
I'm using this to make the focus:
public void focusAt(Point point) {

    if(mCanAe || mCanAf) {

        int areaSize = 200;

        int ll = ((point.x * mActiveArraySize.right) - areaSize) / mTextureView.getWidth();
        int rr = ((point.y * mActiveArraySize.bottom) - areaSize) / mTextureView.getHeight();

        int focusLeft = clamp(ll, 0, mActiveArraySize.right);
        int focusBottom = clamp(rr, 0, mActiveArraySize.bottom);

        Rect newRect = new Rect(focusLeft, focusBottom, focusLeft + areaSize, focusBottom + areaSize);
        MeteringRectangle meteringRectangle = new MeteringRectangle(newRect, 1);
        final MeteringRectangle[] meteringRectangleArr = { meteringRectangle };

        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);

        try {
            mCaptureSession.capture(mPreviewRequestBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {

                    if (mCanAe) {
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, meteringRectangleArr );
                    }

                    if (mCanAf) {
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_REGIONS, meteringRectangleArr );
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
                    }

                    try {

                        mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
                    }
                    catch (CameraAccessException e) {

                        e.printStackTrace();
                    }
                }
            }, mBackgroundHandler);
        }
        catch (CameraAccessException e) { e.printStackTrace(); }
    }
}

This function can't be called during the capture. I thought it would be enough, but sometimes during the capture, Camera2 tries to focus.
Is there a way to disable the focus?
Other question, is it mandatory to lock the focus before capturing? Seems to work fine without doing it, but I'd like to be sure.
EDIT: to capture I'm doing this:
private void capture() {

    try {

        final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
        captureBuilder.addTarget(mImageReader.getSurface());

        // Orientation
        int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

        mCaptureSession.capture(captureBuilder.build(), null, mTakeImageBackgroundHandler);
    }
    catch (CameraAccessException e) {
        e.printStackTrace();
    }

I call the capture() method as soon as a frame is saved.


text:
Q: EOFException when obtaining a Writer object on serilized file I am getting following:
java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at com.Temp.main(Temp.java:62)

Below is the code that I am trying to run:
class Dog implements Serializable {
    private static final long serialVersionUID = 1L;
    int age = 0;
    String color = "Black";
}

public class Temp {
    public static void main(String[] args) {
        FileOutputStream fos;
        ObjectOutputStream oos;
        FileInputStream fis;
        ObjectInputStream ios;
        File doggy;
        try {
            Dog fluffy = new Dog();
            fos = new FileOutputStream("DOG_store.txt");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(fluffy);
            fos.close();
            oos.close();

            doggy = new File("DOG_store.txt");
            FileWriter fw = new FileWriter(doggy); // **This is Causing ISSUE**

            fis = new FileInputStream("DOG_store.txt");
            ios = new ObjectInputStream(fis);
            Dog scrappy = (Dog) ios.readObject();
            fis.close();
            ios.close();
            System.out.println(scrappy.age + " " + scrappy.color);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (ClassNotFoundException cfne) {
            cfne.printStackTrace();
        }
    }

A: when you do FileWriter fw = new FileWriter(doggy); it opens file in write mode and deletes the previous data of file. Thats why whie reading the file it gives EOFException because there is nothing to read in file.
If you do like this  FileWriter fw = new FileWriter(doggy,true); then there will be no error   because it does not delete the previous data of file.


text:
Q: how to show a pop up message in python? hello I just started python and i'm facing a probleme with this code
the probleme is i want the printing part to be in a pop up window message instead of the ide how can i do that ? and thank u.
from tkinter import *
from tkinter import ttk
root=Tk()
root.title('laccroche')
b1=ttk.Button(root,text="entrez le titre:")
b1.pack()
entry1=ttk.Entry(root,width=60)
entry1.pack()

style=ttk.Style()
style.configure('TButton', foreground='blue')
def be():
print("ce texte est un texte "+entry1.get())

b1.config(command=be)
root.mainloop()

A: I'm not sure if this is what you're looking for but you can try using the tkinter messagebox command.
The code will go something like: (I'm not good with French but the first string basically gives the title of the popup window)
def be():
    messagebox.showinfo("Your text","ce texte est un texte "+entry1.get())

Alternatively, if you do not want to have any title for the popup, you can specify the text given as the message as:
def be():
        messagebox.showinfo(message="ce texte est un texte"+entry1.get())


text:
Q: Creating Spree Extension Hey I have tried a lot creating spree extension , but after weeks efforts also I am not getting the desired outcome out of it. I have followed the spreecommerce website on extension tutorial but I didn't found it enough  for a spree beginner.
Please suggest some good spree tutorial links.
Its urgent!!!

A: Simply in terminal in the dir of the spree store.
spree extension <nameofextension>

A: http://www.theroamingcoder.com/?q=node/11
http://blog.endpoint.com/2010/01/rails-ecommerce-spree-hooks-tutorial.html
see also Spree, Rails 3, and theming
http://www.spreecamps.com/devcamps-tutorial


text:
Q: Associatedtype Swift 3 I'm trying understand generics culture in Swift so I've written a small example. But it does not compile.
Error: Generic parameter 'P' could not be inferred
I can't understand for I'm doing wrong.
protocol Protocol_1 {
    associatedtype T
}

protocol Protocol_A {}
struct SomeStruct_2: Protocol_A {}

struct SomeStruct_1: Protocol_1 {
    typealias T = Protocol_A
}

let struct1 = SomeStruct_1()
testFunction(t: struct1) // *Generic parameter 'P' could not be inferred*

func testFunction<P: Protocol_1>(t: P) where P.T : Protocol_A {

}

A: P.T in testFunction cannot conform to Protocol_A, but you can check if its equal to Protocol_A.
func testFunction<P: Protocol_1>(t: P) where P.T == Protocol_A {
}


text:
Q: Create new element with one button effectively i'm trying to create printable polaroid template, but i have a problem with some element, i have sticker container like this :

the screenshot of sticker container :

when i click the picture it will create new element to the polaroid-container, here :

My problem is, how to make its work ? i tried to use this code :
    var counter = 0;
      $('.sticker').on("click", function() {
        $('.cutting-container').append("

");
        $('.sticker-body').draggable({
          containment: $('.polaroid')
        });
      });`

but it will only show one image that i write on .append() , how to make this effectively without create jquery each image ?
UPDATE

full page. As you can see with this code :
    var counter = 0;
      $('.sticker').on("click", function() {
        $('.cutting-container').append("

");
        $('.sticker-body').draggable({
          containment: $('.polaroid')
        });
      });

it will create new element on polaroid-container called sticker-body and it will come with image inside append(). I have class called sticker its for sticker image, what i want is when i click sticker class with ex: image-1 it will show image-1 and if its another sticker class it will show image-2
how do i create this more effectively without create jquery each id (*if i use id per class) ? So i should not create a lot of 'append()` code. Thanks

A: If I understand your question correctly, you are having bunch of stickers that user can select from a template container and add them to another div.
Here is what I have done:

*

*I made a new object. So you are going to deal with a complete new object.

*I made it draggable.

var counter = 0;

$('.sticker').on("click", function() {
  let $sticker = $($(this).html()); // use a cloned object in case you want to eliminate it.
  $('.cutting-container').append($sticker);
   $sticker.draggable({
     containment: $('.polaroid')
   });

});


text:
Q: Transitive ordering of messages in Akka Actors Is there any simple way to enforce transitive ordering of messages in Akka?
For example I have

*

*A sending M1 to C

*A sending M2 to B

*B forwards M2 to C
How do I ensure C gets (or interprets) M1 before M2 in a simple way?

A: There are a few of ways you could do this:

*

*Have C send a reply to A when it receives M1 and delay sending M2 to B before the reply is received.

*Send M2 to C and have C forward it to B

*Put a flag in M2 to say that it depends on M1 and have C stash M2 if it arrives before M1


text:
Q: Using the data-* on input element So i have discovered the data-* attribute and i have been using it with ajax to set the the id's on my link element destination.
Ex;
Display Text

So this way i can create a php function to make my link for non-java users and i use the id attribute and the data-container attribute for my ajax.
It is working fine.
I wanted to do the same with my inputs element but for some reason its not working. The data-* attribute is not showing in the source of the page.
So i must assume that i cant use the data-* attribute with input's
So my question is what element can take the data-* attribute?
or if it is faster to answer witch can't take it?
Tank you StackOverFlow Community! (=
EDIT
The line that output my input from php :
echo '<input id="'.$id.'" type="'.$type.'" name="'.$name.'" size="'.$size.'" class="'.$class.'" value="'.$value.'">

';

Then how i retrieve the value of this data attribute with Jquery for ajax :
var data_type = ($(this).attr("data-type"));

if i do alert(data_type) it is telling me its undefined.

A:
So i must assume that i cant use the data-* attribute with input's

data-* attributes are global , and can be used at input element .

var span = document.createElement("span");
span.innerHTML = document.querySelector("input").dataset.input;
document.body.appendChild(span);
<input data-input="123" />

A: Inputs can take a data element.  Here is a test case:
jsFiddle Demo
HTML:
Click Me

<input type="text" data-container="an_input" />

Div here

js:
$('*').click(function(){
    var d = $(this).data();
  alert(d.container);
  return false;
});

References:
http://ejohn.org/blog/html-5-data-attributes/
http://api.jquery.com/data/

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.


text:
Q: Jquery backup for HTML5's autofocus feature to ensure autofocus in all browsers <textarea type="text" id="message" rows="1" cols="20" name="email" spellcheck="false" autocomplete="off" autofocus required></textarea>

Is there some Jquery that I can implement to ensure that browsers that do not support HTML5 autofocus still autofocus on this textarea? Thanks

A: You could use jQuery's focus:
$(function() {
    $("#message").focus();
});

A:  <script>
    $(function(){
       if (!("autofocus" in document.createElement("input"))) {
         $("#message").focus();
         //document.getElementById('message').focus(); as an alternitive.
       }
    });
 </script>

Will work and not fire for those browsers that support autofocus.
Code gratuitously stolen from diveintohtml5.info

A: Try this..
$(function() {
    $("#message").focusin();
});


text:
Q: If one number from each set is selected at random, then determine $P(Y < X)$ A discrete random variable, $X$, is uniformly distributed between $1$ and $10$ inclusive, and another discrete random variable, $Y$, is uniformly distributed between $5$ and $15$ inclusive. If one number from each set is selected at random, then determine $P(Y < X)$.
I understand that this would mean $$P(X=1)=\frac{1}{10},\;P(X=2)=\frac{1}{10},\;\ldots,\;P(X=10)=\frac{1}{10},$$ and $$P(Y=5)=\frac{1}{10},\;P(Y=6)=\frac{1}{10},\;\ldots,\;P(Y=15)=\frac{1}{10}.$$
How should I start this and answer the question?

A: As mentioned in the comments we need to start with
$P(X=1)=\cdots=P(X=10)=\frac{1}{10}$ and $P(Y=5)=\cdots=P(Y=15)=\frac{1}{11}$.
The answer given by Gregory has the essential elements but was written hastily I suspect and has some errors;) Here is a bit more detail, and hopefully error free:
\begin{eqnarray*}
P(Y<X)
&=&
P\Big(\bigcup_{j=5}^{15}(Y<X,Y=j)\Big)\ \text{(reason: partitioning }(Y<X)\text{ over disjoint sets }(Y=j)\text{)}\\
&&
\sum_{j=5}^{15}P(Y<X,Y=j)\ \text{(reason: probability of union of disjoint sets)}\\
&=&
\sum_{j=5}^{15}P(j<X,Y=j)\ \text{(reason: }Y=j\text{ on each set)}\\
&=&
\sum_{j=5}^{9}P(j<X,Y=j)\ \text{(reason: }X\text{ can only be 1-10)}\\
&=&
\sum_{j=5}^{9}P(j<X)P(Y=j)\ \text{(reason: }X,Y\text{ are independent)}\\
&=&
\sum_{j=5}^{9}\Big(1-P(X\leq j)\Big)P(Y=j)\ \text{(reason: }P(B)=1-P(B^c)\text{)}\\
&=&
\sum_{j=5}^{9}\Big(1-\frac{j}{10}\Big)P(Y=j)\ \text{(reason: }P(X\leq j)=
\frac{1}{10}+\cdots+\frac{1}{10},\ j\text{ times)}\\
&=&
\sum_{j=5}^{9}\Big(1-\frac{j}{10}\Big)\frac{1}{11}\ \text{(reason: }P(Y=j)=\frac{1}{11}\text{)}\\
&=&
\Big(5-\frac{35}{10}\Big)\frac{1}{11} = \frac{15}{110} = \frac{3}{22}
\end{eqnarray*}

A: $$P(Y < X) = \bigcup_i P(Y < X, Y = i) = \bigcup_i P(Y<X | Y = i) P(Y = i) = \sum_{i=5}^{9} \left(1 - \frac{i}{10} \right)\frac{1}{11} = \frac{3}{22}. $$
EDIT:
As was pointed out, I had a typo and the probability $P(Y = i) = 1/11$ and not $1/16$.