text:
Q: Android WebRTC DataChannel is always null and ICE candidates are not sent I'm trying to create an Android app that uses WebRTC data channels for data exchange. The data that I want to send is basic strings. Admittedly, this is my first time looking at WebRTC, and so I am a bit fuzzy on the details. My problem is that whenever I try to create a data channel, it is always null, and ICE candidate requests do not seem to be exchanged with the signalling server. I started from this example that creates a connection to exchange video between two devices and modified it to not exchange video but instead create a data channel.
I looked through a lot of other answers but the vast majority have to do with WebRTC in the browser, and data channel examples are rare to begin with. I also looked through the google chromium source code implementation of WebRTC in c++ to see if anything could be learned but had no luck.
My code is as follows
WebRtcActivity.kt
// imports omitted
class WebRtcActivity : AppCompatActivity() {

    private lateinit var rtcClient: RTCClient
    private lateinit var signallingClient: SignallingClient

    private val sdpObserver = object : AppSdpObserver() {
        override fun onCreateSuccess(p0: SessionDescription?) {
            super.onCreateSuccess(p0)
            signallingClient.send(p0)
            println("session description to string: " + p0.toString()) // prints
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_rtc)

        // camera permission check omitted
        onCameraPermissionGranted()

    }

    private fun onCameraPermissionGranted() {
        rtcClient = RTCClient(
                application,
                object : PeerConnectionObserver() {
                    override fun onIceCandidate(p0: IceCandidate?) {
                        super.onIceCandidate(p0)
                        signallingClient.send(p0)
                        rtcClient.addIceCandidate(p0)
                        println("ice candidate to string: " + p0.toString()) // does not print
                    }

                    override fun onDataChannel(p0: DataChannel?) {
                        super.onDataChannel(p0)
                    }

                }
        )

        signallingClient = SignallingClient(createSignallingClientListener())

        call_button.setOnClickListener { // on-screen button to initiate sending the offer
            rtcClient.call(sdpObserver)
        }
    }

    private fun createSignallingClientListener() = object : SignallingClientListener {
        override fun onConnectionEstablished() {
            println("connection established")
        }

        override fun onOfferReceived(description: SessionDescription) {
            rtcClient.onRemoteSessionReceived(description)
            rtcClient.answer(sdpObserver)
            println("offer received") // prints
        }

        override fun onAnswerReceived(description: SessionDescription) {
            rtcClient.onRemoteSessionReceived(description)
            println("answer received") // prints
        }

        override fun onIceCandidateReceived(iceCandidate: IceCandidate) {
            rtcClient.addIceCandidate(iceCandidate)
            println("signalling client ice candidate") // does not print
        }
    }

RTCClient.kt
// imports omitted
class RTCClient(
        context: Application,
        observer: PeerConnection.Observer
) {

    init {
        initPeerConnectionFactory(context)
    }

    private val iceServer = listOf(
            PeerConnection.IceServer.builder("stun:stun1.l.google.com:19302")
                    .createIceServer()
    )

    private val peerConnectionFactory by lazy { buildPeerConnectionFactory() }
    private val peerConnection by lazy { buildPeerConnection(observer) }

    private fun initPeerConnectionFactory(context: Application) {
        val options = PeerConnectionFactory.InitializationOptions.builder(context)
                .setEnableInternalTracer(true)
                .createInitializationOptions()
        PeerConnectionFactory.initialize(options)
    }

    private fun buildPeerConnectionFactory(): PeerConnectionFactory {
        return PeerConnectionFactory
                .builder()
                .setOptions(PeerConnectionFactory.Options().apply {
                    disableEncryption = true
                    disableNetworkMonitor = true
                })
                .createPeerConnectionFactory()
    }

    private fun buildPeerConnection(observer: PeerConnection.Observer) = peerConnectionFactory.createPeerConnection(
            iceServer,
            observer
    )

    private fun PeerConnection.call(sdpObserver: SdpObserver) {
        val constraints = MediaConstraints().apply {
            //mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))  // with this, the ICE candidate requests actually send, but I am not using audio so i do not think it needs to be here
            mandatory.add(MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true")) // saw this constraint on an answer somewhere, I cannot tell if it is needed/or not
        }

        createOffer(object : SdpObserver by sdpObserver {
            override fun onCreateSuccess(desc: SessionDescription?) {

                setLocalDescription(object : SdpObserver {
                    override fun onSetFailure(p0: String?) {
                    }

                    override fun onSetSuccess() {
                    }

                    override fun onCreateSuccess(p0: SessionDescription?) {
                    }

                    override fun onCreateFailure(p0: String?) {
                    }
                }, desc)
                sdpObserver.onCreateSuccess(desc)
            }
        }, constraints)
    }

    private fun PeerConnection.answer(sdpObserver: SdpObserver) {
        val constraints = MediaConstraints().apply {
            //mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true")) // with this, the ICE candidate requests actually send, but I am not using audio so i do not think it needs to be here
            mandatory.add(MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"))
        }

        createAnswer(object : SdpObserver by sdpObserver {
            override fun onCreateSuccess(p0: SessionDescription?) {
                setLocalDescription(object : SdpObserver {
                    override fun onSetFailure(p0: String?) {
                    }

                    override fun onSetSuccess() {
                    }

                    override fun onCreateSuccess(p0: SessionDescription?) {
                    }

                    override fun onCreateFailure(p0: String?) {
                    }
                }, p0)
                sdpObserver.onCreateSuccess(p0)
            }
        }, constraints)

    }

    private fun createChannel(label: String, peerConnection: PeerConnection?) {
        try {
            val init = DataChannel.Init().apply {
                negotiated = true
                id = 0
            }
            val channel = peerConnection?.createDataChannel(label, init)
            // here, channel is null

            val channelObserver: DataChannelObserver = DataChannelObserver()
            channel?.registerObserver(channelObserver)

        } catch (e: Throwable) {
            e.printStackTrace()
            println("creating channel exception: $e")
        }
    }

    fun call(sdpObserver: SdpObserver) = peerConnection?.call(sdpObserver)

    fun answer(sdpObserver: SdpObserver) = peerConnection?.answer(sdpObserver)

    fun createDataChannel(label: String) = this.createChannel(label, peerConnection)

    fun onRemoteSessionReceived(sessionDescription: SessionDescription) {
        peerConnection?.setRemoteDescription(object : SdpObserver {
            override fun onSetFailure(p0: String?) {
            }

            override fun onSetSuccess() {
            }

            override fun onCreateSuccess(p0: SessionDescription?) {
            }

            override fun onCreateFailure(p0: String?) {
            }
        }, sessionDescription)
    }

    fun addIceCandidate(iceCandidate: IceCandidate?) {
        peerConnection?.addIceCandidate(iceCandidate)
    }
}

SignallingClient.kt
// imports omitted=
class SignallingClient(
    private val listener: SignallingClientListener
) : CoroutineScope {

    private val job = Job()

    private val gson = Gson()

    override val coroutineContext = Dispatchers.IO + job

    private val sendChannel = ConflatedBroadcastChannel<String>()

    init {
        connect()
    }

    private fun connect() = launch {
        val client = OkHttpClient()

        val request = Request.Builder().url("wss://random_ngrok_url").build() // here, I use ngrok since android has a problem with sending cleartext to a non-encrypted location. i also have the signalling server hosted on heroku, and it works the same

        val wsListener = CustomWebSocketListener(listener)

        val ws: WebSocket = client.newWebSocket(request, wsListener)

        listener.onConnectionEstablished()

        val sendData = sendChannel.openSubscription()

        try {
            while (true) {
                sendData.poll()?.let {
                    Log.v(this@SignallingClient.javaClass.simpleName, "Sending: $it")
                    println("signalling client send: $it")
                    ws.send(it)
                }
            }
        } catch (exception: Throwable) {
            Log.e("asd","asd",exception)
        }

        client.dispatcher.executorService.shutdown()
    }

    fun send(dataObject: Any?) = runBlocking {
        sendChannel.send(gson.toJson(dataObject, dataObject!!::class.java))
    }

    fun destroy() {
        job.complete()
    }
}

CustomWebSocketListener.java (forgive me for the java + kotlin mixup, I am more comfortable with java)
// imports omitted
public class CustomWebSocketListener extends WebSocketListener {

    private final SignallingClientListener listener;

    public CustomWebSocketListener(SignallingClientListener listener) {
        super();
        this.listener = listener;
    }

    @Override
    public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosed(webSocket, code, reason);
    }

    @Override
    public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosing(webSocket, code, reason);
    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        webSocket.close(1000, null);
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        super.onMessage(webSocket, text);
        JsonObject j = new Gson().fromJson(text, JsonObject.class);
        if (j.has("serverUrl")) {
            this.listener.onIceCandidateReceived(new Gson().fromJson(j, IceCandidate.class));
        } else if (j.has("type") && (j.get("type")).getAsString().equals("OFFER")) {
            this.listener.onOfferReceived(new Gson().fromJson(j, SessionDescription.class));
        } else if (j.has("type") && (j.get("type")).getAsString().equals("ANSWER")) {
            this.listener.onAnswerReceived(new Gson().fromJson(j, SessionDescription.class));
        }
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
        super.onMessage(webSocket, bytes);
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
    }
}

DataChannelObserver.java
// imports omitted
public class DataChannelObserver implements DataChannel.Observer {

    public DataChannelObserver(){}

    @Override
    public void onBufferedAmountChange(long l) {
        System.out.println("channel buffer amount changed");
    }

    @Override
    public void onStateChange() {
        System.out.println("channel state changed");
    }

    @Override
    public void onMessage(DataChannel.Buffer buffer) {
        System.out.println("channel msg: " + buffer.toString());
    }
}

and finally, the signalling server
'use strict';

const Uws = require('uWebSockets.js');
const uuid = require('uuid');

try {
    let listenSocket;

    let connectedClients = new Map();

    Uws.App({})
        .ws('/socket', {
            message: (ws, message, isBinary) => {
                const wsId = connectedClients.get(ws);
                for (const [socket, id] of connectedClients.entries()) {
                    if (socket !== ws && id !== wsId) {
                        console.log('sending message')
                        socket.send(message, isBinary);
                    }
                }
            },
            open: ws => {
                console.log('websocket opened');
                const wsId = uuid.v4();
                if (!connectedClients.has(ws)) {
                    connectedClients.set(ws, wsId);
                    console.log('added to connected clients: ' + wsId);
                } else {
                    console.log(wsId + ' already exists in connected clients')
                }
            },
        })
        .listen('0.0.0.0', Number.parseInt(process.env.PORT) || 9001, (token => {
            listenSocket = token;
            if (token) {
                console.log(`listening to port ${process.env.PORT || 9001}`);
            } else {
                console.log('failed to listen')
            }
        }))
} catch (e) {
    console.log(e);
    process.exit(1);
}

(I believe that the signalling server works, as it just forwards the requests to the other, and currently I am just testing with two devices. I modeled it off the example signalling server)
The SignallingClientListener and PeerConnectionObserver classes can be found in the example linked above, I did not modify them.
I tried creating the data channel before creating the offer, after creating it, after the connection has been established, and it is always null. I use the negotiated connection since I just want something really basic, and will be able to agree on the ID beforehand.
I've not set up my own STUN/TURN servers as my devices worked with the video calling example and so I imagine they should work with this, but let me know if I'm wrong.
Any help or tips about other possibly easier solutions would be greatly appreciated.
For reference, I am testing on two android 10 devices, and the webrtc version is 1.0.32006.

A: Answering my own question, not entirely but will post what worked for me. Ultimately I could not figure out what was wrong with the code above, I suspect somewhere I was not doing something right with the initialization or requests.
Some of the files are from above and have not been modified, but I'll post them anyways. Also, I had used this article as a starting point.
CustomPeerConnection.java

import android.content.Context;
import android.util.Log;

import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SessionDescription;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

public class CustomPeerConnection {
    private final String TAG = this.getClass().getName();
    private PeerConnection peerConnection;
    private DataChannel dataChannel;
    private SignallingClient client;
    private CustomWebSocketListener wsListener;
    private Executor executor;

    public CustomPeerConnection(Context context, Executor executor) {
        this.executor = executor;
        init(context);
    }

    private void init(Context context) {
        PeerConnectionFactory.InitializationOptions initializationOptions = PeerConnectionFactory.InitializationOptions.builder(context)
                .createInitializationOptions();
        PeerConnectionFactory.initialize(initializationOptions);
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder().setOptions(options).createPeerConnectionFactory();
        List<PeerConnection.IceServer> iceServers = new ArrayList<>();
        iceServers.add(PeerConnection.IceServer.builder("stun:stun2.1.google.com:19302").createIceServer());
        iceServers.add(PeerConnection.IceServer.builder("stun:stun1.l.google.com:19302").createIceServer());
        iceServers.add(PeerConnection.IceServer.builder("turn:numb.viagenie.ca").setUsername("").setPassword("").createIceServer()); // go create your own turn server for free
        PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers);

        peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, new CustomPeerConnectionObserver() {

            @Override
            public void onIceCandidate(IceCandidate iceCandidate) {
                super.onIceCandidate(iceCandidate);
                client.send(iceCandidate);
                peerConnection.addIceCandidate(iceCandidate);
            }

            @Override
            public void onDataChannel(DataChannel dc) {
                super.onDataChannel(dc);
                executor.execute(() -> {
                    dataChannel = dc;
                    dataChannel.registerObserver(new CustomDataChannelObserver());
                    sendMessage(dataChannel, "test");
                });
            }

            @Override
            public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
                super.onIceConnectionChange(iceConnectionState);
                if(iceConnectionState != null){
                    if(iceConnectionState == PeerConnection.IceConnectionState.CONNECTED){
                        Log.d(TAG, "IceConnectionState is CONNECTED");
                    }
                    if(iceConnectionState == PeerConnection.IceConnectionState.CLOSED){
                        Log.d(TAG, "IceConnectionState is CLOSED");
                    }
                    if(iceConnectionState == PeerConnection.IceConnectionState.FAILED){
                        Log.d(TAG, "IceConnectionState is FAILED");
                    }
                }
            }

            @Override
            public void onSignalingChange(PeerConnection.SignalingState signalingState) {
                super.onSignalingChange(signalingState);
                Log.d("Signalling State", signalingState.name());
                if (signalingState.equals(PeerConnection.SignalingState.HAVE_REMOTE_OFFER)) {
                    createAnswer();
                }
            }
        });

        DataChannel.Init dcInit = new DataChannel.Init();
        dataChannel = peerConnection.createDataChannel("dataChannel", dcInit);
        dataChannel.registerObserver(new CustomDataChannelObserver());

        this.wsListener = new CustomWebSocketListener(this);
        this.client = new SignallingClient(wsListener);

    }

    public void sendMessage(DataChannel dataChannel, String msg) {
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        boolean sent = dataChannel.send(new DataChannel.Buffer(buffer, false));
        Log.d("Message sent", "" + sent);
    }

    public void addIceCandidate(IceCandidate candidate) {
        this.peerConnection.addIceCandidate(candidate);
    }

    public void setRemoteDescription(CustomSdpObserver observer, SessionDescription sdp) {
        this.peerConnection.setRemoteDescription(observer, sdp);
    }

    public void createOffer(){
        MediaConstraints constraints = new MediaConstraints();
        constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
        constraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
        constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
        constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
//        constraints.mandatory.add(new MediaConstraints.KeyValuePair("IceRestart", "true"));

        peerConnection.createOffer(new CustomSdpObserver(){
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                super.onCreateSuccess(sessionDescription);

                peerConnection.setLocalDescription(new CustomSdpObserver(), sessionDescription);
                client.send(sessionDescription);
            }

            @Override
            public void onCreateFailure(String s) {
                super.onCreateFailure(s);
                Log.d(TAG, "offer creation failed: " + s);
            }
        }, constraints);
    }

    public void createAnswer() {
        MediaConstraints constraints = new MediaConstraints();
        constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
        constraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
        constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
        constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
//        constraints.mandatory.add(new MediaConstraints.KeyValuePair("IceRestart", "true"));

        peerConnection.createAnswer(new CustomSdpObserver(){

            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                super.onCreateSuccess(sessionDescription);

                peerConnection.setLocalDescription(new CustomSdpObserver(), sessionDescription);
                client.send(sessionDescription);
            }

            @Override
            public void onCreateFailure(String s) {
                super.onCreateFailure(s);
                // Answer creation failed
                Log.d(TAG, "answer creation failed: " + s);
            }
        }, constraints);
    }

    public void close(){
        if(peerConnection == null){
            return;
        }

        if (dataChannel != null) {
            dataChannel.close();
        }
        peerConnection.close();
        peerConnection = null;
    }

}

CustomDataChannelObserver.java
import android.util.Log;

import org.webrtc.DataChannel;

import java.nio.ByteBuffer;

public class CustomDataChannelObserver implements DataChannel.Observer {
    public CustomDataChannelObserver(){
    }

    @Override
    public void onBufferedAmountChange(long l) {

    }

    @Override
    public void onStateChange() {
        Log.d("Channel Observer", "State has changed");
    }

    @Override
    public void onMessage(DataChannel.Buffer buffer) {
        ByteBuffer data = buffer.data;
        byte[] bytes = new byte[data.remaining()];
        data.get(bytes);
        final String message = new String(bytes);
        Log.d("Channel Observer", "msg: " + message);
    }
}

CustomPeerConnectionObserver.java
import android.util.Log;

import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.RtpReceiver;

public class CustomPeerConnectionObserver implements PeerConnection.Observer {
    public CustomPeerConnectionObserver(){

    }

    @Override
    public void onSignalingChange(PeerConnection.SignalingState signalingState) {

    }

    @Override
    public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {

    }

    @Override
    public void onIceConnectionReceivingChange(boolean b) {

    }

    @Override
    public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {

    }

    @Override
    public void onIceCandidate(IceCandidate iceCandidate) {

    }

    @Override
    public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {

    }

    @Override
    public void onAddStream(MediaStream mediaStream) {

    }

    @Override
    public void onRemoveStream(MediaStream mediaStream) {

    }

    @Override
    public void onDataChannel(DataChannel dataChannel) {
        Log.d("CustomPeerConnectionObserver", dataChannel.label());
    }

    @Override
    public void onRenegotiationNeeded() {

    }

    @Override
    public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {

    }
}

CustomSdpObserver.java
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;

public class CustomSdpObserver implements SdpObserver {

    public CustomSdpObserver(){

    }

    @Override
    public void onCreateSuccess(SessionDescription sessionDescription) {

    }

    @Override
    public void onSetSuccess() {

    }

    @Override
    public void onCreateFailure(String s) {

    }

    @Override
    public void onSetFailure(String s) {

    }
}

CustomWebSocketListener.java
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.webrtc.IceCandidate;
import org.webrtc.SessionDescription;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class CustomWebSocketListener extends WebSocketListener {

    public CustomPeerConnection peerConnection;

    public CustomWebSocketListener(CustomPeerConnection peerConnection) {
        this.peerConnection = peerConnection;
    }

    @Override
    public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosed(webSocket, code, reason);
//        System.out.println("Websocket closed");
    }

    @Override
    public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosing(webSocket, code, reason);
        webSocket.close(1000, null);
    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        System.out.println("websocket error: " + t.getMessage());
        webSocket.close(1000, null);
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        super.onMessage(webSocket, text);
        Log.d("socket listener", "received :" + text);
        JsonObject j = new Gson().fromJson(text, JsonObject.class);
//        Log.d("socket listener", "jsonobject keys: " + Arrays.deepToString(j.keySet().toArray()));
        if (j.has("serverUrl")) {
            peerConnection.addIceCandidate(new Gson().fromJson(j, IceCandidate.class));
        } else if (j.has("type") && (j.get("type")).getAsString().equals("OFFER")) {
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.valueOf(j.get("type").getAsString()),
                    j.get("description").getAsString());

            peerConnection.setRemoteDescription(new CustomSdpObserver(), sdp);

        } else if (j.has("type") && (j.get("type")).getAsString().equals("ANSWER")) {
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.valueOf(j.get("type").getAsString()),
                    j.get("description").getAsString());

            peerConnection.setRemoteDescription(new CustomSdpObserver(), sdp);
        }
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
        super.onMessage(webSocket, bytes);
//        System.out.println("bytes msg: " + bytes.hex());
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
//        System.out.println("Websocket opened");

    }
}

SignallingClient.kt
import android.util.Log
import com.google.gson.Gson
import io.ktor.util.KtorExperimentalAPI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket

@ExperimentalCoroutinesApi
@KtorExperimentalAPI
class SignallingClient(
    private val socketListener: CustomWebSocketListener
) : CoroutineScope {

    private val job = Job()
    private val gson = Gson()
    override val coroutineContext = Dispatchers.IO + job
    private val sendChannel = ConflatedBroadcastChannel<String>()

    private val url: String = "" // set your socket url here

    private lateinit var ws: WebSocket
    private lateinit var client: OkHttpClient

    init {
        connect()
    }

    private fun connect() = launch {
        client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        ws = client.newWebSocket(request, socketListener)
        val sendData = sendChannel.openSubscription()
        try {
            while (true) {
                sendData.poll()?.let {
//                    Log.d(this@SignallingClient.javaClass.simpleName, "Sending: $it")
                    ws.send(it)
                }
            }
        } catch (exception: Throwable) {
            Log.e("asd","asd",exception)
        }

        client.dispatcher.executorService.shutdown()
    }

    fun send(dataObject: Any?) = runBlocking {
        sendChannel.send(gson.toJson(dataObject, dataObject!!::class.java))
    }

    fun destroy() {
        ws.close(1000, "destroy called");
        job.complete()
    }
}

WebRtc2Activity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.os.Bundle;
import android.os.Handler;

import com.project.R;

import java.util.concurrent.Executor;

public class WebRtc2Activity extends AppCompatActivity {

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

        Executor g = ContextCompat.getMainExecutor(getApplicationContext());
        CustomPeerConnection peerConnection = new CustomPeerConnection(getApplicationContext(), g);

        Handler h = new Handler();
        h.postDelayed(() -> peerConnection.createOffer(), 3000);
//        peerConnection.createOffer();
    }

}

signalling server is the exact same as the one in the question.
Truth be told, the above code is decent starting code, and needs improvements. The way it's run in the activity is not done well, and there really isn't any error handling or dropped connection checks. I only did so to be able to make sure the mechanism works. So to anyone who may find this useful, do not run it the way I do here, modify it or extend.

A: private fun buildPeerConnectionFactory(): PeerConnectionFactory {
        return PeerConnectionFactory
                .builder()
                .setOptions(PeerConnectionFactory.Options().apply {
                    disableEncryption = true // This is the cause of your null DataChannel and null IceCandidates
                    disableNetworkMonitor = true
                })
                .createPeerConnectionFactory()
    }

I have just figure it out it in about 10 minutes before after been stuck for almost a month, now finally I can have some new progress for my trash project


text:
Q: Python join tables based on '<=' and '>=' I am working on transferring pyspark code to python. In that process i have landed into a challenge wherein i have the below code in spark sql which i need to change to python
select b.id as tno, a.* from dfrno a, dft b where a.v = b.v1 and (a.rno >= b.start_rno and a.rno <= b.end_rno)
Since i am new to python i am not sure how to go about this. And i am eager to understand the methodology since this would be quite interesting. I can use only native python packages. I tried to split this into two steps and complete but the join will effectively do the job only with the >= <= condition. It would be of great help if you can get this resolved.
Below is pictorial representation of the tables and the output required. Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pleiades atmospheric correction I have phr1a and phr1b images (Pleiades) and I need to make atmospheric correction. First, I tried to do this by using Envi FLAASH. by the way, I tried also ERDAS atcor but there was also same conversion problem. I did radiometric correction but I couldn't do atmospheric correction because every time the software has the error of  ACC error:convert7. Does anybody have any idea how to overcome this problem?

A: FLAASH in envi is very sensitive.
1) your result must be saved in other drives (not drive C).
2) you should make a folder for saving FLAASH result specifically.
3) you should enter any name as root name, because the root name box in empty.
4) you should enter a single address for output reflectance file and output directories.
good luck,


text:
Q: Keyboard Layout library to find Neighboring Keys given an input key (java preferable) Does anyone know of a library (preferably java) that can give me neighboring keys given a key input for US_ENGLISH standard keyboard?
E.g. if I input the character 'd', I should get the following characters returned: [w,e,r,s,f,x,c,v].
Alternatively a grid manipulation api would work too (so that I can instantiate a grid with a qwerty keyboard layout and use it to find my neighbors).
Note 1: I am using the words 'character' and 'key' synonymously to refer to characters.
Note 2: I know I can hard-code a method to map the 50-or-so primary keys to their neighbors. I am looking for a better solution.
Thank You.

A: I agree with BlueNovember but in case you want a more "mathematical" solution check this. First you create a grid of characters and then you return all of them that has a distance smaller than 2 from the key passed... Kinda useless but it's a nice exercise :)
public class Test {

    static String chars = "qwertyuiopasdfghjkl;zxcvbnm,.";

    public static void main(String[] args) {
        System.out.println(getNeighboringKeys('f'));
        System.out.println(getNeighboringKeys('u'));
        System.out.println(getNeighboringKeys('m'));
        System.out.println(getNeighboringKeys('q'));
    }

    public static String getNeighboringKeys(char key) {
        StringBuffer result = new StringBuffer();
        for (char c : chars.toCharArray()) {
            if (c!=key && distance(c,key)<2) {
                result.append(c);
            }
        }
        return result.toString();
    }

    public static double distance(char c1, char c2) {
        return Math.sqrt(Math.pow(colOf(c2)-colOf(c1),2)+Math.pow(rowOf(c2)-rowOf(c1),2));
    }

    public static int rowOf(char c) {
        return chars.indexOf(c) / 10;
    }

    public static int colOf(char c) {
        return chars.indexOf(c) % 10;
    }
}

A: I gave up on this and just let the user choose what keys are suitably adjacent. In this project an enum Key relates each command  to a keyCode, and this dialog lets the user change the mapping. The result is saved in Preferences.

A: I'd be surprised if there is a solution better than Note 2.
What would the library be doing underneath, if not this? Keys don't have any relationship to each other you can build from.

A: Be careful when you do this.  For example, next to D are ZERSFXCV, not WERSFXCV if you're in France.  And if you use Dvorak, it's YFGIHXBM.  If you're in Turkey, it might be  567ORUTK.


text:
Q: Why does Ask Ubuntu have a special Top Bar? I was looking at how the new top bar looks on every Stack Exchange and I wondered.
Why do the Linux enthusiasts have a different top bar unique of all Stack Exchange websites ?

A: The Ask Ubuntu top bar ties in with the Canonical sites and their design, as it has for quite a long time now - this site has had a different top bar since the Canonical redesign.
The new bar will go in, but the exact design and integration have not been completed, as it is not as easy to integrate it into the Canonical look and feel.


text:
Q: Extract text lines as displayed in textview Is it possible to get each line of a multiline text as it will appear in a textview of a fixed width, with a font, size, alignment without actually drawing the textview ?
My Text is stored in a string. I can apply different font, size, alignment for the text. When passing it to my api, I want to split it into a list of Strings just how it was displayed in the app. Is this possible ?
In the view the text is formatted using the following:
    TextView textView = new TextView(getContext());

    LayoutParams textLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    if (itemWidth > 0) {
        textLayoutParams.width = itemWidth;
    }

    if (itemHeight == -1) {
        textLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
    }

    textLayoutParams.leftMargin = xPosition;
    textLayoutParams.topMargin = yPosition;
    textView.setLayoutParams(textLayoutParams);
    textView.setPaintFlags(Paint.ANTI_ALIAS_FLAG);
    font = getFontName(font);

    if (!StringUtils.isEmpty(font)) {
        CalligraphyUtils.applyFontToTextView(getContext(), textView, CalligraphyConfig.get(), "fonts/" + font);
    }

    if (!StringUtils.isEmpty(color))
        textView.setTextColor(Color.parseColor(color));

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, (int)size );

    if (alignment.equalsIgnoreCase("center")) {
        textView.setGravity(Gravity.CENTER);
    } else if (alignment.equalsIgnoreCase("left")) {
        textView.setGravity(Gravity.START);
    } else if (alignment.equalsIgnoreCase("right")) {
        textView.setGravity(Gravity.END);
    } else if (alignment.equalsIgnoreCase("left_center")) {
        textView.setGravity(Gravity.START | Gravity.CENTER);
    }

    addView(textView);

For multi line strings, it will display on different lines. In a background process, I want to know which substring was displayed on 1st line, which substring was displayed on second line and so on. Is this even possible ?


text:
Q: Magento2: Product collection multiple attribute filter issue I need to get a product collection to filter multiple attributes.
Forexample:
First: color multi select filter(attribute) values: 23, 25, 26.
Second: system multi-select filter(attribute) values: 27, 28.
I am getting filter values in one array and need to filter in the collection.
There are comma separated $list = 23, 25, 26,27, 28
    In the controller file:
$list =  $this->getRequest()->getParam('list', false);
$filter_ids = explode(",",$list);

$productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryProducts = $productcollection->create()->addAttributeToSelect('*')->addAttributeToFilter('color', array('in',$filter_ids))->addAttributeToFilter('system', array('in',$filter_ids))->load();

I am not getting a result in this way.
where I am wrong. Please suggest to me.
Thanks

A: Check with my code,
$list =  $this->getRequest()->getParam('list', false);
$filter_ids = explode(",",$list);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryProducts =  $productcollection->create()->addAttributeToSelect('*')->addAttributeToFilter(
        array(
            array('attribute'=> 'color','in' => $filter_ids),
            array('attribute'=> 'system','in' => $filter_ids),
        )
    );


text:
Q: Bookmarking Script? It's for a user to "save" a story he's read. I got a snippet of code from SO a few days ago but, I can't seem to get it to work. I want to snatch the url from the page a user is currently viewing, insert the url in a MySQL DB and output the url back to client under a favorite section on the website. Any ideas?
When I try the code below, I get a T String error.
  Index.php
  <?php
  function curPageURL() {
   $pageURL = 'http';
      if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}  $pageURL .= "://";
      if ($_SERVER["SERVER_PORT"] != "80") {   $pageURL .= $_SERVER ["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

  } else {   $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI";
  }
  return $pageURL;
  }

 ?>

    <html>
    <body>
    <form action="storeBookmark.php?url=<?php echo curPageURL();" method="GET"> <input type="submit" value="Submit" />
    </form>
    </body>
    </html>

   <?php
   $url = $_GET['url'];

   $dbc = mysqli_connect('xxxx', 'xxxx', 'xxxx', 'xxxx')
   or die('Error connecting to MySQL server');

  $query = "INSERT INTO xxxx (url)".    "VALUES('$url')";

 $result = mysqli_query($dbc, $query)   or die('Error.');

 mysqli_close($dbc);
 ?>

A:     <form action="storeBookmark.php?url=<?php echo curPageURL();?>" method="GET"> <input type="submit" value="Submit" />

Added in closing php tag for curPageURL() function call.
You should also not store unsanitized user data in your database. Since you're using mysqli you should use a prepared statement.
<?php

$link = mysqli_connect('xxxx', 'xxxx', 'xxxx', 'xxxx') or die('Error connecting to MySQL server');

$url = $_GET['url'];

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, 'INSERT INTO table1 (url) VALUES(?)')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $url);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}


text:
Q: how to redirect non php extension url to php extension url htaccess? I have added .php extension to all my pages in wordpress through functions.php.
My Code -
<?php
// Do NOT include the opening PHP tag

// Add .PHP to page permalinks
add_action('init', 'ss_php_pages', -1);
function ss_php_pages() {
    global $wp_rewrite;

    if ( !strpos($wp_rewrite->get_page_permastruct(), '.php')){
            $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.php';
    }

    $wp_rewrite->flush_rules();
}

// Remove slash from page permalinks
add_filter('user_trailingslashit', 'no_page_slash_on_ss',66,2);
function no_page_slash_on_ss($string, $type){
    global $wp_rewrite;

    if ($wp_rewrite->using_permalinks() && $wp_rewrite->use_trailing_slashes==true && $type == 'page'){
        return untrailingslashit($string);
    }else{
       return $string;
      }
}

Now I want to redirect my old link (example.com/demo) to new link (example.com/demo.php)..
I have many pages there so I can't add redirection for each manually.
Additional information:
I have added .php extension to my Wordpress pages (example.com/demo + .php). Now My Old Links (example.demo or example.com/anything) which were without .php, got 404 because I have added .php to them so they have modified. Now I want to redirect my all old links like example.com/demo to example.com/demo.php or example.com/xyz to example.com/xyz.php to not to loss traffic or getting broken link.

A: You can redirect your non-php pages to php using RewriteRule directive in your WordPress htaccess.
At the top of your htaccess file , put the following rule :
RewriteEngine on

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ /$1.php [L,R=301]

A: Could you please try following htaccess Rules. Make sure htaccess is present in root folder.
Make sure to clear your browser cache before testing your URLs.
RewriteEngine on
##User is using wordpress without this rule it was adding .php to home page too which was NOT needed, hence this rule is been added.
RewriteRule ^/?$ / [R=301,END]

##Major rules for links which are non php and should be served with php format files.
RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
RewriteCond %{REQUEST_URI} !\.php/?$ [NC]
RewriteRule ^(.*)/?$ $1.php [L,R=301]

For JS/CSS rewrite: You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.


text:
Q: which is best amoung Cloud Firestone and Realtime Database in FIrebase for working with large and complex data structure I am developing android and IOS app with web backend admin support for an organisation oriented employee, tasks and issue management system. issues and the task will be posted by any public people and issue will be addressed and solved by the organization people.
my app will have dynamic keyword filtering over the new issue posting and an algorithm will keep running to identify the issue categories dynamically from the issues being posted.
my app or the search result and filters should be fast in retrieving the data and it should not affect my application performance. I didn't know which one is good to use for a case like this.

A: I use the Realtime database for an large iOS app that contains users, jobs for users, favourites, messages etc. So I need the database to show results in realtime as well as being reliable.
The best features for a big app like the one I have built are the
offline capabilities
If the user goes offline, the database is still responsive and persists data to the disk which resynchronises when connection is established.
Data synchronization
All of my users on the app can see changes happening instantly such as notifications and messages, job updates etc. It's reliable and stops any overlapping potential risk.
https://firebase.google.com/docs/database/
Additionally, it sounds like you will benefit from the easy JSON structure that Firebase Realtime database offers to build categories etc.
I use a lot of filters in my iOS app and the calls to the database return results almost instantly given a connection is established; its very flexible.
In terms of reliability
Cloud Firestore is currently in beta. Stability in a beta product is not always the same as that of a fully launched product, where as Realtime Database is a mature product.

A: Use Fire-Base Realtime database if your apps are not going to serve more than 1000 people.
Because Fire-base Realtime doesn't perform much complex and fast queries like Fire-Base FireStore. And you can not upgrade your app if your app is based on RealTime database.
FireStore has more features that Realtime database.
You can go and check the difference between both of them:-
https://firebase.google.com/docs/database/rtdb-vs-firestore


text:
Q: utf 8 character not showing on android I've made a web app that relies on some utf-8 characters rendered in <pre> tags. The app also stores text files locally the SD card of the android device and meant to be viewed later in a text viewer app (any).
The characters appear as intended everywhere (mac, pc, iphone) but on Android phones. These superscript characters (7⁴  7⁶  7⁷  7⁹  7⁺) don't display in text files (when loaded from the SD card) or in web browsers.
How can I fix this or use a similar character to accomplish the job? The most important thing is to have two numbers side-by-side (7⁷) but look visually different, that don't require any markup, but will look different in plain text as well.


text:
Q: AutoConfigureTestDatabase is deprecated What is the alternative since AutoConfigureTestDatabase is deprecated? I am trying to test my database using a memory one. Where can I locate the changelog?

A: Replace import from:
org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase
to:
org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase


text:
Q: Error Building Hadoop 2.6.4 on OS X: [INFO] Apache Hadoop Annotations .......................... FAILURE [  1.212 s]
I'm getting an error building Hadoop 2.6.4 on OS X.  I tried various ways of skipping the Javadoc code, but it's still not working.
$ mvn clean package -DskipTests -DskipDocs -Dmaven.javadoc.skip=true

$ mvn clean package -Pdist -DskipTests -Dtar -Dmaven.javadoc.skip=true

$ mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T08:41:47-08:00)
Maven home: /opt/local/share/java/maven3
Java version: 1.8.0_05, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.4", arch: "x86_64", family: "mac"

E.g. Here's sample output.
[ERROR]   symbol:   class AnnotationDesc
  location: class ExcludeHandler
/Users/davidlaxer/hadoop/hadoop-common-project/hadoop-annotations/src/main/java/org/apache/hadoop/classification/tools/RootDocProcessor.java:[226,11] error: cannot find symbol
[ERROR]   symbol:   class Doc
  location: class ExcludeHandler
/Users/davidlaxer/hadoop/hadoop-common-project/hadoop-annotations/src/main/java/org/apache/hadoop/classification/tools/ExcludePrivateAnnotationsJDiffDoclet.java:[36,11] error: cannot find symbol
[ERROR]   symbol:   variable LanguageVersion
  location: class ExcludePrivateAnnotationsJDiffDoclet
/Users/davidlaxer/hadoop/hadoop-common-project/hadoop-annotations/src/main/java/org/apache/hadoop/classification/tools/ExcludePrivateAnnotationsJDiffDoclet.java:[42,16] error: cannot access Doclet
[ERROR]   class file for com.sun.javadoc.Doclet not found
/Users/davidlaxer/hadoop/hadoop-common-project/hadoop-annotations/src/main/java/org/apache/hadoop/classification/tools/ExcludePrivateAnnotationsStandardDoclet.java:[35,11] error: cannot find symbol


text:
Q: pythonpath working in Powershell but not in Ubuntu I am learning about the Python path, and worked out how to use it in powershell. I used os.environ to find that what the variable PYTHONPATH was set to. In both powershell and ubuntu, they were set to the same place. I then navigated to this folder, and created a python file called hello.py with a simple function. When I called this from powershell with
python
import hello
hello.hello()

the code ran. However, when I run in ubuntu the same code, I get ModuleNotFound error message. This confused me because when I ran echo $PYTHONPATH it gave the same value as in powershell when I used the os.environ method. To double check I also ran the following in my ubuntu terminal
python3
import os
os.environ['PYTHONPATH']

and this also gaves the same location.
What am I doing wrong?
EDIT: output from running py --list-paths
ethanh@LAPTOP-E642IMV7:/mnt/c$ py --list-paths
/usr/bin/py:16: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working
  from collections import Iterable
usage: py [-x] [-l] [-c PRE_CMD] [-C POST_CMD] [-V] [-h] [expression]
py: error: unrecognized arguments: --list-paths


text:
Q: Python on keypress ScrolledText.get() When I press a key and print the text on the ScrolledText, the last key I pressed is not showing in the ScrolledText.get(). Anyone help me.

A: I found the solution. It's just .bind_all


text:
Q: Selecting conditions with jooq In SQL, I can execute a query of type:
SELECT cost > 1000 AS above_k, name FROM products;

Giving me a list:
+---------+--------+
| above_k | name   |
+---------+--------+
| true    | Gold   |
| false   | Silver |
+---------+--------+

How can I model a similar query using jooq? I cannot do this (obviously):
ctx.select(Tables.PRODUCTS.COST.gt(1000))

Since, there is no method select(Condition condition). Or if I just wanted to:
SELECT cost*0.9 AS discounted_cost FROM products;

Is there a way to do this using jooq?

A: SQL 1:
SELECT cost > 1000 AS above_k, name
FROM products;

jOOQ 1:
ctx.select(field(PRODUCTS.COST.gt(1000)).as("above_k"), PRODUCTS.NAME)
   .from(PRODUCTS)
   .fetch();

See DSL.field(Condition)
SQL 2:
SELECT cost*0.9 AS discounted_cost
FROM products;

jOOQ 2:
ctx.select(PRODUCTS.COST.mul(0.9).as("discounted_cost"))
   .from(PRODUCTS)
   .fetch();

See Field.mul(Number) or Field.multiply(Number)


text:
Q: Shortest way to extract last 3 characters of base (minus suffix) filename I'm trying to set a variable in an sh script to the last 3 characters of the base name of a file (by base name I mean without the path and without the suffix). I've succeeded in doing this but, purely out of curiosity, I'm wondering if there is a shorter, single command I can use. Originally I had a one-liner with awk, but it was rather long. Currently I have this two-line script (assuming a complete filename is in $1):
filebase=`basename "$1"`
lastpart=`echo -n ${filebase%.*} | tail -c3`

So for example, "/path/to/somefile.txt" ends up with "ile" in $lastpart.
Can I somehow combine basename and the bit to strip the suffix into a single command, and is there a way to send it to tail (or something else I can use) without using a pipe? The suffix is unknown so I can't base it as a parameter to basename.
The main goal isn't actually so much to be as short as possible, as to be as readable at a glance as possible. The actual context of all of this is this question on Superuser, where I'm trying to come up with a reasonably simple answer.

A: That's a typical job for expr:
$ file=/path/to/abcdef.txt
$ expr "/$file" : '.*\([^/.]\{3\}\)\.[^/.]*$'
def

If you know your file names have the expected format (contains one and only one dot and at least 3 characters before the dot), that can be simplified to:
expr "/$file" : '.*\(.\{3\}\)\.'

Note that the exit status will be non-zero if there's no match, but also if the matched part is a number that resolves to 0. (like for a000.txt or a-00.txt)
With zsh:
file=/path/to/abcdef.txt
lastpart=${${file:t:r}[-3,-1]}

(:t for tail (basename), :r for rest (with extension removed)).

A: If you can use perl:
lastpart=$(
    perl -e 'print substr((split(/\.[^.]*$/,shift))[0], -3, 3)
            ' -- "$(basename -- "$1")"
)

A: sed works for this:
[user@host ~]$ echo one.two.txt | sed -r 's|(.*)\..*$|\1|;s|.*(...)$|\1|'
two

Or
[user@host ~]$ sed -r 's|(.*)\..*$|\1|;s|.*(...)$|\1|' <<<one.two.txt
two

If your sed doesn't support -r, just replace the instances of () with \( and \), and then -r isn't needed.

A: var=123456
echo "${var#"${var%???}"}"

###OUTPUT###

456

That first removes the last three characters from $var then removes from $var the results of that removal - which returns the last three characters of $var.  Here are some examples more specifically aimed at demonstrating how you might do such a thing:
touch file.txt
path=${PWD}/file.txt
echo "$path"

/tmp/file.txt

base=${path##*/}
exten=${base#"${base%???}"}
base=${base%."$exten"}
{
    echo "$base"
    echo "$exten"
    echo "${base}.${exten}"
    echo "$path"
}

file
txt
file.txt
/tmp/file.txt

You don't have to spread this all out through so many commands. You can compact this:
{
    base=${path##*/} exten=
    printf %s\\n "${base%.*}" "${exten:=${base#"${base%???}"}}" "$base" "$path"
    echo "$exten"
}

file
txt
file.txt
/tmp/file.txt
txt

Combining $IFS with setting shell parameters can also be a very effective means of parsing and drilling through shell variables:
(IFS=. ; set -f; set -- ${path##*/}; printf %s "${1#"${1%???}"}")

That will get you only the three characters immediately preceding the first period following the last / in $path. If you want to retrieve only the first three characters immediately preceding the last . in $path (for instance, if there is a possibility of more than one . in filename):
(IFS=.; set -f; set -- ${path##*/}; ${3+shift $(($#-2))}; printf %s "${1#"${1%???}"}")

In both cases you can do:
newvar=$(IFS...)

And...
(IFS...;printf %s "$2")

...will print what follows the .
If you don't mind using an external program you can do:
printf %s "${path##*/}" | sed 's/.*\(...\)\..*/\1/'

If there is a chance of a \newline character in the filename (not applicable for the native shell solutions - they all handle that anyway):
printf %s "${path##*/}" | sed 'H;$!d;g;s/.*\(...\)\..*/\1/'

A: If perl is available, I find it can be more readable than other solutions, specifically because its regex language is more expressive and it has the /x modifier, which allows for writing clearer regexs:
perl -e 'print $1 if shift =~ m{ ( [^/]{3} ) [.] [^./]* \z }x' -- "$file"

This prints nothing if there is no such match (if the basename has no extension or if the root before the extension is too short).  Depending on your requirements, you can adjust the regex.  This regex enforces the constraints:

*

*It matches the 3 characters before the final extension (the part after and including the last dot).  These 3 characters can contain a dot.

*The extension can be empty (except for the dot).

*The matched part and the extension must be part of the basename (the part after the last slash).

Using this in a command substitution has the normal issues with removing too many trailing newlines, a problem which also affects Stéphane's answer.  It can be dealt with in both cases, but is a little easier here:
lastpart=$(
  perl -e 'print "$1x" if shift =~ m{ ( [^/]{3} ) [.] [^./]* \z }x' -- "$file"
)
lastpart=${lastpart%x}  # allow for possible trailing newline

A: Python2.7
$ echo /path/to/somefile.txt | python -c "import sys, os; print '.'.join(os.path.basename(sys.stdin.read()).split('.')[:-1])[-3:]"
ile

$ echo file.one.two.three | python -c "import sys, os; print '.'.join(os.path.basename(sys.stdin.read()).split('.')[:-1])[-3:]"
two

A: I think this bash function, pathStr(), will do what you are looking for.
It doesn't require awk, sed, grep, perl or expr. It uses only bash builtins so it's quite fast.
I've also included the dependent argsNumber and isOption functions but their functionalities could be easily incorporated into pathStr.
The dependent function ifHelpShow is not included as it has numerous subdependencies for outputting the help text either on the terminal commandline or to a GUI dialog box via YAD. The help text passed to it is included for documentation. Advise if you would like ifHelpShow and its dependents.
function  pathStr () {
  ifHelpShow "$1" 'pathStr --OPTION FILENAME
    Given FILENAME, pathStr echos the segment chosen by --OPTION of the
    "absolute-logical" pathname. Only one segment can be retrieved at a time and
    only the FILENAME string is parsed. The filesystem is never accessed, except
    to get the current directory in order to build an absolute path from a relative
    path. Thus, this function may be used on a FILENAME that does not yet exist.
    Path characteristics:
        File paths are "absolute" or "relative", and "logical" or "physical".
        If current directory is "/root", then for "bashtool" in the "sbin" subdirectory ...
            Absolute path:  /root/sbin/bashtool
            Relative path:  sbin/bashtool
        If "/root/sbin" is a symlink to "/initrd/mnt/dev_save/share/sbin", then ...
            Logical  path:  /root/sbin/bashtool
            Physical path:  /initrd/mnt/dev_save/share/sbin/bashtool
                (aka: the "canonical" path)
    Options:
        --path  Absolute-logical path including filename with extension(s)
                  ~/sbin/file.name.ext:     /root/sbin/file.name.ext
        --dir   Absolute-logical path of directory containing FILENAME (which can be a directory).
                  ~/sbin/file.name.ext:     /root/sbin
        --file  Filename only, including extension(s).
                  ~/sbin/file.name.ext:     file.name.ext
        --base  Filename only, up to last dot(.).
                  ~/sbin/file.name.ext:     file.name
        --ext   Filename after last dot(.).
                  ~/sbin/file.name.ext:     ext
    Todo:
        Optimize by using a regex to match --options so getting argument only done once.
    Revised:
        20131231  docsalvage'  && return
  #
  local _option="$1"
  local _optarg="$2"
  local _cwd="$(pwd)"
  local _fullpath=
  local _tmp1=
  local _tmp2=
  #
  # validate there are 2 args and first is an --option
  [[ $(argsNumber "$@") != 2 ]]                        && return 1
  ! isOption "$@"                                      && return 1
  #
  # determine full path of _optarg given
  if [[ ${_optarg:0:1} == "/" ]]
  then
    _fullpath="$_optarg"
  else
    _fullpath="$_cwd/$_optarg"
  fi
  #
  case "$_option" in
   --path)  echo "$_fullpath"                            ; return 0;;
    --dir)  echo "${_fullpath%/*}"                       ; return 0;;
   --file)  echo "${_fullpath##*/}"                      ; return 0;;
   --base)  _tmp1="${_fullpath##*/}"; echo "${_tmp1%.*}" ; return 0;;
    --ext)  _tmp1="${_fullpath##*/}";
            _tmp2="${_tmp1##*.}";
            [[ "$_tmp2" != "$_tmp1" ]]  && { echo "$_tmp2"; }
            return 0;;
  esac
  return 1
}

function argsNumber () {
  ifHelpShow "$1" 'argsNumber "$@"
  Echos number of arguments.
  Wrapper for "$#" or "${#@}" which are equivalent.
  Verified by testing on bash 4.1.0(1):
      20140627 docsalvage
  Replaces:
      argsCount
  Revised:
      20140627 docsalvage'  && return
  #
  echo "$#"
  return 0
}

function isOption () {
  # isOption "$@"
  # Return true (0) if argument has 1 or more leading hyphens.
  # Example:
  #     isOption "$@"  && ...
  # Note:
  #   Cannot use ifHelpShow() here since cannot distinguish 'isOption --help'
  #   from 'isOption "$@"' where first argument in "$@" is '--help'
  # Revised:
  #     20140117 docsalvage
  #
  # support both short and long options
  [[ "${1:0:1}" == "-" ]]  && return 0
  return 1
}

RESOURCES

*

*http://tldp.org/LDP/abs/html/arrays.html

*https://stackoverflow.com/questions/23207168/a-semantics-for-bash-scripts/23208014#23208014


text:
Q: How to get column chart in angular using highcharts using dynamic data I am implemented the high charts in angular js  ,It is working fine with hard coded data but it is not working when data came from web service dynamically .
In my controller :
$scope.months = [];
                $scope.retail = [];
                $scope.wholesale = [];

                $scope.fetchChart = function(){
                    $scope.chartConfig = {
                            title: {
                                text: ""
                            },

                            options: {
                                chart: {
                                    type: 'column'
                                },
                                plotOptions: {
                                    series: {
                                      stacking: ''
                                    }
                                  },
                                legend: {
                                    layout: 'vertical',
                                    align: 'topleft',
                                    verticalAlign: 'top',
                                    borderWidth: 1
                                }
                            },
                            xAxis: {
                                categories: $scope.months
                            },
                            credits: {
                                enabled: true
                            },
                            series: [{
                                name: 'Retail',
                                data: $scope.retail
                            },
                            {
                                name: 'Wholesale',
                                data: $scope.wholesale
                            }
                            ],

                            loading: false
                    }
                };

                $http.get(http://localhost:8080/abc/pqr/mno/getData).success(function(response) {
                    $scope.data = angular.fromJson(response);
                    $scope.comlete = false;
                    var count=0;
                    for(var i = 0; i < $scope.data.length; i++){
                        count++;
                        $scope.months.push($scope.data[i].month);
                        $scope.retail.push($scope.data[i].retail);
                        $scope.wholesale.push($scope.data[i].wholesale);
                        if(count == $scope.data.length){
                            $scope.fetchChart();
                            $scope.comlete = true;
                        }
                    }

                    $scope.toggleHighCharts = function () {
                        this.chartConfig.useHighStocks = !this.chartConfig.useHighStocks
                    }

                    $scope.$watch("comlete",function(){
                        alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
                      },true);

                    $scope.reflow = function () {
                        $scope.$broadcast('highchartsng.reflow');
                    };

                });

                $scope.chartTypes = [
                                     {"id": "line", "title": "Line"},
                                     {"id": "spline", "title": "Smooth line"},
                                     {"id": "area", "title": "Area"},
                                     {"id": "areaspline", "title": "Smooth area"},
                                     {"id": "column", "title": "Column"},
                                     {"id": "bar", "title": "Bar"},
                                     {"id": "pie", "title": "Pie"},
                                     {"id": "scatter", "title": "Scatter"}
                                     ];

                $scope.dashStyles = [
                                     {"id": "Solid", "title": "Solid"},
                                     {"id": "ShortDash", "title": "ShortDash"},
                                     {"id": "ShortDot", "title": "ShortDot"},
                                     {"id": "ShortDashDot", "title": "ShortDashDot"},
                                     {"id": "ShortDashDotDot", "title": "ShortDashDotDot"},
                                     {"id": "Dot", "title": "Dot"},
                                     {"id": "Dash", "title": "Dash"},
                                     {"id": "LongDash", "title": "LongDash"},
                                     {"id": "DashDot", "title": "DashDot"},
                                     {"id": "LongDashDot", "title": "LongDashDot"},
                                     {"id": "LongDashDotDot", "title": "LongDashDotDot"}
                                     ];

                $scope.chartSeries = [
                                      {"name": "Retail", "data": $scope.retail, type: "column"},
                                      {"name": "Wholesale", "data": $scope.wholesale, type: "column"}
                                      ];

In My Html :
<div>
    <highchart id="chart1"  config="chartConfig"></highchart>
</div>

In Controller for the statements:
$scope.data = angular.fromJson(response);

I got the data as
[{"wholesale":"1","retail":"0","month":"Jan"},
{"wholesale":"2","retail":"0","month":"May"},
{"wholesale":"0","retail":"1","month":"Jun"},
{"wholesale":"0","retail":"2","month":"Jul"}]

In Controller for the statements:
$scope.$watch("comlete",function(){
                        alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
                      },true);

I got data as:
["Jan","May","Jun","Jul"]---["0","0","1","2"]=-=--["1","2","0","0"]

and in series:
series: [{  name: 'Retail',
            data: $scope.retail
        },
        {   name: 'Wholesale',
            data: $scope.wholesale
        }
        ],

when i replace data: $scope.retail with data: [250,500,1500,1800]//$scope.retail and data: $scope.wholesalewith data: [700,800,200,1300]//$scope.wholesale it is working .How can i get the chart with dynamic data.

A: Answer to the Problem:-
I solved the problem by myself. I am answering  the solution for my future reference and in case it helps somebody having the same requirement.
$scope.$watch("comlete",function(){
                        alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
                      },true);

In the above statements the $scope.retail and $scope.wholesale data as string of arrays ,
the statement
 series: [{
           name: 'Retail',
           data: $scope.retail
           },
           {
           name: 'Wholesale',
           data: $scope.wholesale
           }
           ],

series is not accepting the data as string ,By converting the string of numbers into numbers (converting string to number type) then it is accepting the series .
the answer statements are :
if(angular.isNumber($scope.data[i].retail))
{
 $scope.retail.push($scope.data[i].retail);
}else{
    $scope.retail.push(+$scope.data[i].retail);
    }
if(angular.isNumber($scope.data[i].wholesale))
{
$scope.wholesale.push($scope.data[i].wholesale);
}else{
$scope.wholesale.push(+$scope.data[i].wholesale);
}

instead of
$scope.retail.push($scope.data[i].retail);
 $scope.wholesale.push($scope.data[i].wholesale);

These two statement in for loop.


text:
Q: Select with specific attributes Lets say we have 3 tables: products, attributes and details.
products
id name price
1  pr1  120
2  pr2  140
3  pr3  200
4  pr4  165

attributes
id name
1  color
2  guarantee
3  resolution
4  year
5  contrast ratio

details
id productId attributeId value
1  1         1           grey
2  1         2           yes
3  2         1           black
4  2         4           2011
5  2         5           70 000:1
6  4         2           no

And want for example to select all products with color = black, year = 2011 and contrast ratio = 70 000:1. In this example the result would be product with id = 2. What would be the mysql syntax for that?
SELECT * FROM products, details WHERE products.id = details.productId
AND details.attributeId = 1 (For the first attribute)
AND details.attributeId = 4 (For the second and third attribute?)
...

A: Use
SELECT *
FROM products p
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 1 ) d1 ON p.ID = d1.productid
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 4 ) d4 ON p.ID = d4.productid
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 5 ) d5 ON p.ID = d5.productid
WHERE
d1.value = 'black' AND
d4.value = '2011' AND
d5.value = '70 000:1'


text:
Q: Get data from a JSON multi-level I have searched and read a lot of different forums to manage JSON data
i have tried many things, but none of them works ;(
{"data": {"results": [{"qid_data": {"custom_id": "XXXXXX", "labels": "YYYYY", "meta": "{}", "bbox": [73, 57, 128, 516], "obj_id": "ZZZZZZ"}, "qid": "WWWWWWWW"}], "error": 0}}

I would like to get the values of:
custom_id, labels, bbox, objet_id, qid
Right now I have the following code (for example for custom_id)
$json_output = json_decode($data);
foreach ($json_output as $json_result) {
echo "custom_id:".$json_result->data->results->qid_data->custom_id;
}

I have tried all the variations possible.
$json_result->results->qid_data->custom_id;
OR
$json_result->results->qid_data->custom_id;
OR
$json_result->data->results->custom_id;
OR
$json_result->results->custom_id;
I never get the result, always an error
If someone can help on how to export with an example for
data custom_id, bbox, qid

A: {"data": {"results": [{"qid_data": {"

does not equal
$json_result->results->qid_data

it equals
 $json_output->data->results[0]->qid_data

notice the square bracket showing results is a list
{"data": {"results": [{"qid_data": {"
                     ^

It looks like what you want is to iterate that list
foreach ($json_output->data->results as $result) {
    echo "custom_id:".$result->qid_data->custom_id;
}


text:
Q: Attempt to compare nil with number on object.x coordinate I you all, when I try to reload a scene in CORONA SDK using the director class, I get "Attempt to compare nil with number" on
if vec.x < _W/2-180 then

where vec is
local vec = display.newImage("main_char.png", _W/2-180, _H/2+300)
vec.x = _W/2-180
vec.y = _H/2+300
localGroup:insert(vec)

I sincerely I haven't find out how to solve it.

A: OK so I can't see any typos, and the code is indicating that vec.x is nil (vec is not nil since the error would be attempt access global vec nil, and _W is not nil because the error would say attempt to perform arithmetic on nil. Can't see anything wrong with what you show, so cause is in code not shown.
I would print(type(vec.x)) anywhere that you access vec.x (after you set it, after you insert it in localGroup, just before your condition check): search for all places where vec.x is set, one of them must be setting it to something nil (like vec.x = someFunction(...) and someFunction returned nil).


text:
Q: Need an example of "lengthened, curtailed, and altered forms of words."
The perfection of Diction is for it to be at once clear and not mean. The clearest indeed is that made up of the ordinary words for things, but it is mean... A certain admixture, accordingly, of unfamiliar terms is necessary. These, the strange word, the metaphor, the ornamental equivalent, etc., will save the language from seeming mean and prosaic, while the ordinary words in it will secure the requisite clearness. What helps most, however, to render the Diction at once clear and non-prosaic is the use of the lengthened, curtailed, and altered forms of words.

This extract is from Aristotle's Poetics and as you may have noticed they articulate his idea of an ideal Poetic Diction. I am having trouble understanding the last line and would greatly benefit if one could give an example of pairs of words that have opposing attributes (the attributes being lengthened and curtailed).

A: This question is so broad to me...and I don't think he meant that one word could be lengthened and curtailed... But I'll give it a go:
1) lengthened= awesomesauce
2) curtailed= "ish" (noun or adjectival)
3) altered= shiznit
As to whether these are all clear and non-prosaic, that's for the reader to determine...


text:
Q: PPL get Compiling Errors when run command I need to run some ppl code in ppl command.
Here is the code:
service tar0_starter

    function start
        const pathFolder= OS.consol?.ask_string ("Please enter at path of file:") if_null: error
        const my_folder = directory.creat(directory_path.create (pathFolder))
            if not my_folder.exists then
            OS.out.write_line("the folder dont found")
            exit script
            .

        my_folder.file_list( include_child_directories=no) ( const file_list=result,const error=error)
            if error isnt null then
                OS.out.write_line("""folder not available""")
                exit script
            .

        if file_list is not null then
            repeate for each file in file_list
            const nameFile=file.name.to_string
            var pathFilestring =pathFolder.to_string & "\\" & nameFile.to_string
            const fileC file =fa_file .create_from_valid_string (pathFile.to_string)
            se_text_file_IO.restore_lines_from_text_file (file=fileC) (const text_in_file=result ,const read_error =error)
            nameFile.split  (split_by ="." ) ( const type =result)
            const checkType = type.last
            if const checkType is not null then
                if checkType=v "vm" then
                    if text_in_file is not null then
                        OS.out write_line ("""check file {{nameFile}}""")
                            repeat for each continent in text_in_file
                                if continentis not null then
                                    continent.split(split_by = " ")(constmerge=result)
                                        const word=merge.first
                                         if word is not null
                                            if word=v "you" then
                                                OS.out write_line ("""{{continent}}""")
                                            .
                                        .
                                .
                    .
                .
            .
        .
            OS_process.exit_with_success
    .
.

I copy this code from ppl tutorial (mean that it's need to work well..)
When I run this code I get many errors:
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_assistant.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_commands.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_compiler.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_core.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_ext.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_paiom.par'
Restoring library repository from file 'C:\Program Files\ppl-2018-01-23\ppl_lib\ppl_projects.par'
Warning

Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: Id or Id path required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: ')' required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 12
       position: 13
    instruction: if error  >>> isnt null then
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 18
       position: 12
    instruction: repeate  >>> for each file in file_list
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: Id or Id path required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: ')' required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: Id or Id path required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: ')' required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 25
       position: 13
    instruction: if const  >>> checkType is not null then
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 28
       position: 14
    instruction: OS.out  >>> write_line (fa_mutable_string.create.append("check
                  file ").append_scalar_or_scalar_value(nameFile).to_string)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 30
       position: 24
    instruction: if continentis  >>> not null then
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: '=' required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: ')' required. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
        line no: 35
       position: 20
    instruction: OS.out  >>> write_line (fa_mutable_string.create.append_scalar
                 _or_scalar_value(continent).to_string)
    description: Rest of line is invalid and ignored. [parser]

Error
       location: Service tar0_starter (tar0)
    description: '.' or '. service' required. [parser]

Parser         :    0.204 sec.
Total time     :    0.242 sec. (empty .class dir + create .par file:    0.242 sec.)
Warning
       location: Type unknown (unknown)
    description: File 'C:\project0\tar0\work\ppl\source_code\tar0\hello.vm' is
                 invalid because its extension is undefined or different from '
                 ppl'. Note that files starting with '---' are silently ignored
                 . [libraries_warning]
Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: Id or Id path required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: ')' required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 11
       position: 72
    instruction: my_folder.file_list ( include_child_directories=no) ( const fi
                 le_list >>> =result,const error=error)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 12
       position: 13
    instruction: if error  >>> isnt null then
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 18
       position: 12
    instruction: repeate  >>> for each file in file_list
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: Id or Id path required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: ')' required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 22
       position: 81
    instruction: se_text_file_IO.restore_lines_from_text_file (file=fileC) (con
                 st text_in_file >>> =result ,const read_error =error)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: Id or Id path required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: ')' required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 23
       position: 50
    instruction: nameFile.split  (split_by ="." ) ( const type  >>> =result)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 25
       position: 13
    instruction: if const  >>> checkType is not null then
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 28
       position: 14
    instruction: OS.out  >>> write_line (fa_mutable_string.create.append("check
                  file ").append_scalar_or_scalar_value(nameFile).to_string)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 30
       position: 24
    instruction: if continentis  >>> not null then
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: '=' required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: ')' required. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 31
       position: 52
    instruction: continent.split(split_by = " ")(constmerge >>> =result)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
        line no: 35
       position: 20
    instruction: OS.out  >>> write_line (fa_mutable_string.create.append_scalar
                 _or_scalar_value(continent).to_string)
    description: Rest of line is invalid and ignored. [parser]
Error
       location: Service tar0_starter (tar0)
    description: '.' or '. service' required. [parser]Press any key to continue . . .

I tried looking for this language in google but nothing, I have no idea what is wrong in this code.
I found out only one site: ppl site.
someone can help me?
Thanks


text:
Q: CssParameter stroke-width min max value Geoserver I wonder if there is a minimum value for the stroke width parameter since I've a LineSymbolizer with stroke 0.1 but i want it to be thinner so i change the value to 0.05 but i dont see any difference on the map when the lines are drawn.
PS: sorry my english

A: The css values are in pixels so you probably won't see much change with fractional values. Try using 0 as I think GeoServer handles that as a special case.
Further information on SLD can be found at http://docs.geoserver.org/stable/en/user/styling/sld-cookbook/lines.html


text:
Q: Compiling TypeScript using gulp is creating an unwanted destination folder I am trying to get Gulp to transpile my .ts files in my /dev directory and move the transpiled .js file to a /build directory.
The desired structure is as follows:
/dev
 - index.ts
/build
 - index.js

What is actually occuring looks like this:
/dev
 - index.ts
/build
 - /dev
    - index.js

As you can see the dev folder is being duplicated. The relevant code in gulpfile.js is as follows:

var gulp = require('gulp');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('./tsconfig.json');

// gulp ts
gulp.task('ts', function () {
  return tsProject.src('dev/**/*.ts')
    .pipe(ts(tsProject))
    .pipe(gulp.dest('build/'));
});

I can get my other build tasks to behave in the desired manner but for whatever reason the TypeScript task is giving me grief.

A: I solved my problem. Adding "rootDir": "dev" to the compilerOptions in tsconfig.json made the gulp task behave as expected.
An unexpected side-effect also occurred and the TypeScript compiler started throwing errors stating that it could not find modules that it previously had no problem finding before. I explicitly added /// <reference path="../typings/tsd.d.ts" /> to my .ts files and was back in business.


text:
Q: Aligning popup window near the button clicked I have a custom popup window by a layout. I have to give a x,y coordinates to appear popup window after a_btn click. This can be different locations in different phones.
But I want to show the popup window always above and touching the the a_btn
How can I implement this.Help me
My code for showing the popup window :
a_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());
            popup.showAtLocation(relative, Gravity.NO_GRAVITY, coordinateTop, 100);
            //popup.showAsDropDown(location_popup_view,  2, 2);

        }
    });

A: Use this code will help you
a_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             Rect r = locateView(v);
    LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());
            popup.showAtLocation(layout, Gravity.TOP | Gravity.LEFT, r.right, r.bottom);

        }
    });

    public static Rect locateView(View v) {
            int[] loc_int = new int[2];
            if (v == null)
                return null;
            try {
                v.getLocationOnScreen(loc_int);
            } catch (NullPointerException npe) {
                return null;
            }
            Rect location = new Rect();
            location.left = loc_int[0];
            location.top = loc_int[1];
            location.right = loc_int[0] + v.getWidth();
            location.bottom = loc_int[1] + v.getHeight();
            return location;
        }

A: I used popup.showAsDropDown(a_btn,0,0);
instead of
popup.showAtLocation(relative, Gravity.NO_GRAVITY, coordinateTop, 100);
and gave xoff and yoff.
a_btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popup_view = lInflater.inflate(R.layout.popup_a, null);
        final PopupWindow popup = new PopupWindow(popup_view,200,200,true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new ColorDrawable());
        popup.showAsDropDown(a_btn,0,0);

    }
});


text:
Q: I have installed the grails appengine plugin, I use intellij, how can I get intellj to quit yelling at me for jdo errors? So,
I am trying to integrate a grails app, with google app engine, all using intellij. I successfully built the grails app, and I installed the app engine plugin successfully. But, now all my domain classes have JDO errors.
Intellij has built in support for app engine, but I couldn't quickly figure out a way to integrate it with my grails app. So I just used the grails command line.
Ideally I would like to use the intellij plugin, but at this point I just want the errors to disappear.
How do I get my jdo errors to go away in my intellij grails app?
And if your feeling really helpful:
How do I use the intellij app engine module to integrate with my grails app?
Thanks

A: Can you give an example of the error or a screenshot? If it's an inspection you can disable it via an intention action shortcut (Alt+Enter) while standing on the code with an error/warning. When menu opens, press the right arrow for the sub-menu where you can disable it. If it's a result of language injection feature, you can try to un-inject the language using the same intention action.
Feel free to vote for the built-in Grails App Engine support in IntelliJ IDEA.


text:
Q: Assistance with getRandomCode Can anyone help me with my code, as described below, i need to make a function called getRandomCode to take 10 codes from a text file, read them and then randomly select one as the secret code. I started but im stuck a need some help moving forward
A function (getRandomCode) that, takes as an input a four-element array of integers
(code). The function will then proceed to open the file codes.txt and try to read in
at most 10 four digit codes. If the file could not be opened, the function should return
false. Otherwise, the function proceeds as follows:
– Read each line of the file and place it in an array (I recommend an array of 10
strings).
– Once the codes have been read, you should seed the random number generator
(srand(time(0))) and use rand() to select a random number between 0 and the
number of codes you read. Hint: think about how your file processing loop will
keep track of the number of codes read.
– Once you have selected a random code, you must copy the digits in to the cor-
responding elements of the four-element array code. To do this you will need to
convert a character to a number. For example, since every character is one digit
we just subtract '0' from the character in position zero of the selected codes
string, and assign the result to code[0].
– Once the code array has been populated, we return true indicating success.
You may safely assume that the file is formatted in such a way that there is exactly
one code per line. You may not, however, assume there are exactly 10 codes in the file.
This is what i have so far :
int getRandomCode(int code[4])
{
ifstream inFile;
inFile.open("codes.txt");
int getCode[10];
int a = 0;

if(!inFile){
    cout<<"Error opening output file"<< endl;
    return -1;
}
while(!inFile.eof())
{
    getline(inFile, getCode[a], '');
    srand(time(0));
    int randomInt = (rand(getCode));
}

}

A: Preferred Method for Reading Many Integers
Here is a code fragment for reading in multiple integers, space or newline separated, and placing into a database:
int value;
std::vector<int> database;
while (inFile >> value)
{
  database.push_back(value);
}

You can treat std::vector as an array, such as value = database[3];.  The std::vector works well with std::sort also.
Limiting Input Quantity
You can add some extra code to limit the quantity of numbers read:
const size_t MAXIMUM_INTEGERS = 10;
size_t quantity = 0;
int value;
std::vector<int> database;
while ((quantity < MAXIMUM_INTEGERS) && (inFile >> value))
{
  database.push_back(value);
  ++quantity;
}

Reading Into an Array
If you must use an array (because of assignment restrictions), the code is similar to the above limiting code:
const size_t MAXIMUM_INTEGERS = 10;
size_t quantity = 0;
int value;
int array[MAXIMUM_INTEGERS];;
while ((quantity < MAXIMUM_INTEGERS) && (inFile >> value))
{
  array[quantity] = value;
  ++quantity;
}

Reading Strings
Reading strings instead of integers uses the same method / pattern:
std::string number_as_text;
size_t quantity_read = 0;
std::vector<std::string> database;
while (std::getline(inFile, number_as_text))
{
  database.push_back(number_as_text);
  ++quantity_read;
}


text:
Q: Is there a way to get the cmdlet for data deduplication when running an Unoptimization job? I deactivated data deduplication on one of my drives because it doesn't work well with the backup system.
I then started an unoptimization job in Administrative PowerShell. After that I realized I didn't put the priority up high so the job runs faster since there is no load on that server at the moment. So I tried stopping the job and got this:
PS C:\Windows\system32> Stop-DedupJob
Stop-DedupJob : The term 'Stop-DedupJob' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Stop-DedupJob
+ ~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Stop-DedupJob:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

I was able to do Get_DedupJob at first but now I get the same error as if the cmdlet were removed.... But an Unoptimization Job is still running...
How can I use the cmdlet without re-enabling the deduplication on the volume?

A: For some reason those cmdlet are availible using the 64 bit version of powershell. It is  shown as Windows PowerShell in the menu, without the trailling (x86). If it is not shown in the applications menu just search for it.
You should then have access to the cmdlet for deduplication.

A: Make sure the Deduplication module is imported in Powershell, otherwise the commands will not be available:
Import-Module Deduplication


text:
Q: What's the difference between "...THE English bookstores in Paris" and "...English bookstores in Paris"? Is it okay to use "the" before "English bookstores" in the following sentence? If yes, how is it different from a sentence without "the"?

You can buy it from the English bookstores in Paris.

You can buy it from English bookstores in Paris.

A: If someone says, "You can buy it from the English bookstore in Paris", the sentence implies there is only one, or one specific, book store in Paris.
If they say, "The English bookstores" in Paris, it would imply that Paris is somehow known for its bookstores... they are special enough to warrant 'the'.
What someone would normally say is "... from an English bookstore in Paris' or, depending on the situation, "... and English bookstore when we get to (or go to) Paris."
I want to say that you can't say "from English Bookstores in Paris", but you can. It would be an odd context. Perhaps...
John: I would really like to get this book, but I can't find it at any of the local French bookstores.
Sue: You can get it from English bookstores in Paris.
That is doable... but I wouldn't recommend anyone but a native speaker try it.