text:
Q: I want change the default button text in sharepoint 2010 i want to change the default text on the button in the newpost.aspx page but i couldn't find the button on the page . when i select the button the whole webpart is highlighted.
please help me on .

A: I do not think there is a "setting" that allows you to do that. Most likely you would have to use some jQuery/Javascript to do this.


text:
Q: Java , Socket, sending messages I'm trying to make a multiplayer game, but first i want to try it with a simple scanner and print code
i have two files, "cl.java" is the client , "server.java" is the server.
WHAT AM I TRYING TO DO ?
a client send a message to other client asking for a game
this initial message does not run in my code , i am thinking that i can not use the clientThread.sendText(un + " iWantToPlay"); outside the class ConnectThread
WHAT DO U THINK ?
the error happens on this code:
        public void sendText(String text) {
        try {
            oos.writeObject(text);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

with the oos.writeObject(text);
this is Server.java
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();

public static void main(String[] args) {
    new Server();

}

public Server() {
    // ServerSocket is only opened once !!!

    try {
        serverSocket = new ServerSocket(6000);

        System.out.println("Waiting on port 6000...");
        boolean connected = true;

        // this method will block until a client will call me
        while (connected) {
            Socket singleClient = serverSocket.accept();
            // add to the list
            ServerThread myThread = new ServerThread(singleClient);
            allClients.add(myThread);
            myThread.start();
        }

        // here we also close the main server socket
        serverSocket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

class ServerThread extends Thread {
    Socket threadSocket;
    String msg;
    boolean isClientConnected;
    InputStream input;
    ObjectInputStream ois;
    OutputStream output;
    ObjectOutputStream oos; // ObjectOutputStream

    public ServerThread(Socket s) {
        threadSocket = s;
    }

    public void sendText(String text) {
        try {
            oos.writeObject(text);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {

        try {
            input = threadSocket.getInputStream();
            ois = new ObjectInputStream(input);
            output = threadSocket.getOutputStream();
            oos = new ObjectOutputStream(output);

            // get the user name from the client and store
            // it inside thread class for later use
            // msg = (String) ois.readObject();
            msg = (String) ois.readObject();

            for (ServerThread t : allClients)
                t.sendText(msg);

            isClientConnected = true;
            System.out.println("connect ... ");

            // System.out.println(msg);
            // for(ServerThread t:allClients)
            // t.sendText("User has connected...");

            // send this information to all users
            // dos.writeUTF(userName + " has connected..");
            // for(ServerThread t:allClients)
            // t.sendText(msg);

            while (isClientConnected) {

                try {
                    msg = (String) ois.readObject();
                    System.out.println(msg);

                    for (ServerThread t : allClients)
                        t.sendText(msg);
                } catch (Exception e) {

                }
            }
            // close all resources (streams and sockets)
            ois.close();
            oos.close();
            threadSocket.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}
this is the cl.java
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;

static ConnectThread clientThread;
boolean isConnected;

static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
static String un;
static String op = "none";
static int turn = 1;

public static void main(String[] args) {
    boolean running = true;

    System.out.print("Enter a username: ");
    un = scanner.nextLine();

    System.out.print("invite or wait ?");
    msg = scanner.nextLine();

    if (msg.equalsIgnoreCase("invite")) {
        System.out.print("Enter an opponent: ");
        op = scanner.nextLine();
    }

    new cl();

    if (op.equalsIgnoreCase("amjad")) {
        clientThread.sendText(un + " iWantToPlay");
    }

}

public String getWord(String line,int i) {
    String arr[] = line.split(" ", 2);
 return arr[i];

}

public cl() {
    connectUser();
}

public void connectUser() {
    clientThread = new ConnectThread();
    clientThread.start();

}

class ConnectThread extends Thread {
    InputStream input;
    OutputStream output;
    ObjectOutputStream oos;
    Socket s;

    public void sendText(String text) {
        try {
            oos.writeObject(text);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            s = new Socket(HOST, PORT);
            output = s.getOutputStream();
            oos = new ObjectOutputStream(output);

            isOnline = true;
            isConnected = true;

            new ListenThread(s).start();

/*              while (isOnline) {
                    msg = scanner.nextLine();
                    clientThread.sendText(un + ": " + msg);
                }
*/
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class ListenThread extends Thread {

    Socket s;
    InputStream input;
    ObjectInputStream ois;

    public ListenThread(Socket s) {
        this.s = s;
        try {
            input = s.getInputStream();
            ois = new ObjectInputStream(input);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        while (isConnected) {
            try {
                final String inputMessage = (String) ois.readObject();
                String user;
                user = getWord(inputMessage,1);
                String message = getWord(inputMessage,2);

                /*if (!user.equals(un)) {
                    System.out.println(inputMessage);
                }*/

                if (message.equalsIgnoreCase("iwanttoplay")) {
                    System.out.println(user + " wants to play, accept? y\n");
                    msg = scanner.nextLine();
                    clientThread.sendText(un + " " + msg);
                }
                else if (message.equalsIgnoreCase("yesiwanttoplay")) {
                    System.out.println(un + " accepted invitation, "  + un + " against " + user);
                    turn = 1;
                    play(un,user);
                }
                else if (message.equalsIgnoreCase("noidontwanttoplay")) {
                    System.out.println(user + " denied invitation.. ");
                }
                else if (message.equalsIgnoreCase("x") || message.equalsIgnoreCase("o")) {
                    System.out.println(user + " played .. " + message);
                    turn = 1;
                    play(un,user);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

public void play(String me, String him) {
    if (turn == 1) {
        System.out.println("your turn,... play a move..x or o ..");
        msg = scanner.nextLine();
        clientThread.sendText(un + " " + msg);
        turn = 2;
    }
}

}
this is my error
Exception in thread "main" java.lang.NullPointerException
at cl$ConnectThread.sendText(cl.java:68)
at cl.main(cl.java:38)

A:
xception in thread "main" java.lang.NullPointerException
  at cl$ConnectThread.sendText(cl.java:68)

You should be able to figure this out yourself. The line in question appears to be
oos.writeObject(text);

and so clearly oos is null at that point.
You don't need StackOverflow to sort out NullPointerExceptions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как можно объединить эти методы c#? public static int Method1(IEnumerable<int> a, int b)
{
    var sum = 0;
    foreach (var x in a)
    {
        sum += b * x;
        b++;
    }
    return sum;
}

public static int Method2(IEnumerable<int> a, int b)
{
    var sum = 0;
    foreach (var x in a)
    {
        sum += b * x;
        b = 4 - b;
    }
    return sum;
}

Может я могу передавать действие которое можно сделать с b? (b = b + 1, b = 4 - b)
public static int Method(IEnumerable<int> a, int b, ??? calculation)
{
    var sum = 0;
    foreach (var x in a)
    {
        sum += b * x;
        b = calculation;
    }
    return sum;
}

A: Как вариант можно передавать лямбду, для этого используем делегат.
public delegate int Operation(int x);

public static int Calculate(IEnumerable<int> a, int b, Operation calculation) {
     var sum = 0;
    foreach (var x in a)
    {
        sum += b * x;
        b = calculation(b);
    }
    return sum;
}

делегат определяет сигнатуру лямбды - возвращаемое значение и принимаемые параметры.
Далее, передаём параметром третьим параметром лямбду, которая на каждой итерации цикла выполнит операцию, описанную в вашей лямбда-функции.
Полный пример:
using System;
using System.Collections.Generic;

class Program
{
    public delegate int Operation(int x);

    public static int Calculate(IEnumerable<int> a, int b, Operation calculation) {
         var sum = 0;
        foreach (var x in a)
        {
            sum += b * x;
            b = calculation(b);
        }
        return sum;
    }

    static void Main() {

        var a = new List<int> {1,2,3,4,5,6,7,8,9};
        int b = 1;
        Console.WriteLine(Calculate(a, b, (x) => b * 2));
    }
}


text:
Q: Not seeing "Create Graph" and "Add Application" options after installing Neo4j Desktop I'm absolutely new to Neo 4j Desktop/ Database. I installed the latest version(1.4.15) and after installing the application on OSX (12.4), i'm not seeing the options to "create a Graph". I followed the steps from here -> https://neo4j.com/download-thanks-desktop/?edition=desktop&flavour=osx&release=1.4.15&offline=false.
I also tried installing it another mac (same OS version) and got the same problem. Am i missing some installation steps because all the get started videos show the option right after installing and opening the application.
This is what i see now

This is what i expected

A: The Add Graph option creates a new graph. You can do it from the Add button dropdown, in the recent version.
Use Local DBMS option to create a new local database.


text:
Q: VS Team Services & Git for Windows error "fatal: Authentication failed ..." Running Git for Windows and the Git Credential Manager on a shared, 4 user, developer VM.
Upon cloning a repository, the GCM kicks in and authenticates me, but Git still reports fatal: Authentication failed ...
I can see in my Team Services (previously VSO) account that the GCM created a new personal access token:
Git: https://company.visualstudio.com/ on SHARED-VM-HOSTNAME
I've revoked previous ones and it creates a new one, so that mechanism is working.
Git (version 2.10) and the GCM don't seem to be playing ball. We have it working elsewhere on other machines.
It works for only one shared user RDP'ed onto this VM.
Just asking IT to reinstall latest versions of all software (again, again).
IP web traffic I think is routing directly/no proxy.
Any ideas?

A: My colleague sent me the wrong Git repository URL!
Bad version:
https://oursubdom.visualstudio.com/DefaultCollection/SomeProjectII
Good version:
https://oursubdom.visualstudio.com/DefaultCollection/_git/SomeProjectII
Not the first time he's done that, either. Ugh.


text:
Q: array.remove() giving IndexOutOfBoundsException I am trying to delete an item from an array (obv, if the array contains it) but it is always giving me an IndexOutOfBoundsException while trying to remove it.
I don't think this question is the same as the one pointed out in the comment section, beacause I was trying to figure out why is this giving me an error in this specific scenario.
I've been searching any solution that could possibly solve it but I found nothing, so I hope someone here is able to tell my why is this happening.
The array I am trying to edit is an Integer array (converted from an String array). Let me show you some code.
for (final Alarm alarm : allAlarms) {
    ArrayList<Integer> activos = IntegerArrayConverter.fromString(alarm.getActiveTags());
    if (activos.contains(idTag)) {
        activos.remove(idTag);
        alarm.setActiveTags(IntegerArrayConverter.fromArrayList(activos));
        app.updateAlarmActiveTags(alarm);
    }
}

It is crashing where it says:
active.remove(idTag);

When the app reaches that line, my array is size 1 and its only value is 255. The idTag value is also 255. I don't know where is the error.
Thank you in advance!

SOLUTION:
As they told me in the comments section, I moved the creation of the ArrayList outside the for loop and also used:
activos.remove(Integer.valueOf(idTag));

instead of:
activos.remove(idTag);

A: The ArrayList class has 2 overloads method to remove. One with an integer parameter, that
  removes the item at that index, and one with an Object parameter.Overload resolution in Java always starts without consideration of boxing and unboxing.
Therefore it gives priority to the remove(int) overload.
Should pass index to the remove method of Arraylist. trying replacing  line  with
activos.remove(0);
or
activos.remove(new Integer(255));
It is not recommended to use ArrayList.remove() when iterating over elements

A: ArrayList class has 2 methods
first is: list.remove(index):- its remove index value
second is : list.remove(object): - its remove particular object
In interger type arraylist to remove particular object from arraylist
Java Code
use this code
 if(list.contains(255)){

        list.remove(Integer.valueOf(255));
    }

A: Avvappa Hegadyal mentioned correctlly that remove can be by index (type int) or by object (some non primitive type).
You have encountered IndexOutOfBoundException, because the first overload method has been called (removing element by id) - but In your array there is no index 255 (you have only one element with index 0)
If you want to remove the element 255. Than make sure that the type of the variable idTag is Integer (instead of int). So the second overloaded method will be called.


text:
Q: Git workflow for local commits, upstream commits and deployment I know there are a lot of posts about git workflows, but I couldn't find exactly what I'm looking for: recommendations about best practices for the following workflow:
I have a web application that deployed via git. The application developers release updates via a public git repo. I also have my own changes that need to be applied. What would be the best way to handle this?
What I've been doing: I created a local deployment repo, cloned from upstream. This is served via gitolite, so it's a bare repo. I have a clone of this repo, on which I apply changes, and push them back to the deployment repo. When changes are published to the upstream repo, I've been incorporating them into this clone, using the recommended command:
git fetch && git pull --rebase

I then push to the deployment repo. The problem is that I start getting a ton of merge conflicts on any files that I've changed. The same file will give me many conflicts during the rebase. I'm looking for an approach that can be more or less automated, but I don't quite get git enough to understand what the problem is.
Can any git gurus offer some advice? Let me know if anything needs clarification. Thanks.

A: I don't want to know and remember crappy, ugly, stupid, "original" Git-jargoon, so I'll write recipe in the form of "needed actions", task of translating it to command I leave for you
Preparation
Send your current workflow to dustbin
Actions

*

*You have to have one repo with two branches (vendor and own). Vendor branch linked to remote repo of upstream, your branch is single place, where you store own changes. Branch Own must be created from Vendor, in order to get common parent for all files in both branches, files in Own  have to be patched with your changes

*Sync with upstream performing by updating Vendor branch from remote and merging with Own branch after it (changes from Vendor merged to Own)

You'll have conflicts only for changed by both sides (you and upstream) files on merge stage

A: Your current workflow would be fine if you dropped the --rebase from git pull. Then pull will do a merge (the default) instead of a rebase, and you will have fewer conflicts. Of course, there will always be situations where git cannot resolve conflicts on its own, so the process cannot be fully automated.
The problem is that rebase takes many steps, going back through your entire history and resolving each change that you've made on top of upstream. This is unnecessary for your scenario, and even counter-productive because it makes it impossible to tell when your changes were made relative to upstream's changes. Merges will work better because they take only one step and do not have to go back very far in the history (only to the previous merge).
If you're still getting more conflicts than you would like when you're doing merges, you will have to find ways to reduce the diff between your revision and upstream (which you can easily check with git diff after doing a merge), or move your changes to places that upstream does not modify very often (or that do not exist in upstream).


text:
Q: Is this correct: $\ln({(-1)}^{2x-1})=(2x-1)\ln(-1)$? I would expect the answer to be positive, but it appears otherwise for some values of $x \geq 1$.
Here is a simple C++ code that I have used in order to test this:
#include <complex>
#include <iostream>

void test(double x)
{
    complex<double> i(0,1);
    complex<double> res1 = (2*x-1)*log(i*i);
    complex<double> res2 = log(pow(i*i,2*x-1));
    cout<<res1<<endl;
    cout<<res2<<endl;
}


text:
Q: How to reformat an auto formatted number using JQuery Hello Im fairly new to Javascript/JQuery. I wanted to autoformat a number while it was being inputted.
I used a Jquery plugin for the same -
<script src="simple.money.format.js"></script>
And calling it using
$('.money').simpleMoneyFormat();
I want it be reformatted when I hit a button (Save) so that the value can be saved into the database.
Any help would be much appreciated.

A: You can use the submit event handler, the code will be called when the user hits the submit button, and before the data sent to the server
$('#your-form-id').submit(function () {
    $('.money').simpleMoneyFormat();
});

A: See the following fiddle: https://jsfiddle.net/EliteSystemer/wv3sxo3j/
$('button').on("click", function() {  //Submit
  var m = $('.money').val();  //Get input value
  m = m.replace(/,/g, "");  //Remove commas
  $('.money').val(m);  //Update input value
  ...send to server
});


text:
Q: How do I attach multiple HTML files to a zip file in R? I want to create a zip file which will contain multiple HTML (created from markdown) files. Here is an example of what I would like to do and the code:
Path of Files
 [1] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60457557.html"
 [2] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60083983.html"
 [3] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60009765.html"

I then convert these three files to a variable. Let's call it attachments, how do I create a zip file where I can place the attachments?
What I tried attachments_markdown is the variable where all the path names of my files are.
zip("Drill_Down.zip", files = attachments_markdown)

However, nothing showed up. See below

A: You can use the zip function to create zip files. Something like this:
zip("name_of_your_zip_file.zip", files = normalizePath(attachments))

Have a look at the ?zip help page for more details.
Note that Windows uses \ in file paths to indicate folders, but in R you will need to use either / or escape the backslash to \\ - so I added normalizePath() to the answer Mikael's suggestion which will take care of that for you in the attachments.


text:
Q: Web API call throwing error java.net.SocketTimeoutException I have one Android project which I developed in Kotlin + MVP architecture. It has total 30 API calls in the project but sometimes it throws socket timeout error randomly from any of one API. I don't know is it a problem in Server or API or Kotlin-MVP or Rx2AndroidNetworking?
Below I'm showing you to call product list web API call in Kotlin + MVP.
This same project I developed in iOS and this error does not throw so it does not fault on Server or API development. I think this problem occurred in Rx2AndroidNetworking library.
Does anyone have any idea or faced this problem in past?

java.net.SocketTimeoutException

failed to connect to / (port 80) after 120000ms: isConnected failed: ETIMEDOUT (Connection timed out)
   at libcore.io.IoBridge.isConnected(IoBridge.java:232)
   at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
   at libcore.io.IoBridge.connect(IoBridge.java:122)
   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
   at java.net.Socket.connect(Socket.java:884)
   at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:70)
   at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:238)
   at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:158)
   at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:256)
   at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
   at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
   at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
   at okhttp3.RealCall.execute(RealCall.java:77)
   at com.rx2androidnetworking.Rx2InternalNetworking$SimpleANObservable.subscribeActual(Rx2InternalNetworking.java:187)
   at io.reactivex.Observable.subscribe(Observable.java:10981)
   at io.reactivex.internal.operators.observable.ObservableDoOnEach.subscribeActual(ObservableDoOnEach.java:42)
   at io.reactivex.Observable.subscribe(Observable.java:10981)
   at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
   at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
   at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
   at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:154)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
   at java.lang.Thread.run(Thread.java:818)

ProductInteractor.kt
class ProductInteractor @Inject internal constructor(apiHelper: ApiHelper, preferenceHelper: PreferenceHelper) : BaseInteractor(apiHelper = apiHelper, preferenceHelper = preferenceHelper), ProductMVPInteractor {

override fun getProductList(pagingAndSortingInfo: PagingAndSortingInfo?, searchBy: String, categoryIds: String) =
        apiHelper.performProductListApiCall(pagingAndSortingInfo, searchBy, categoryIds)
}

ProductPresenter.kt (it.showError(t!!.message!!) line throwing socket timeout Toast message)
class ProductPresenter<V : ProductGridMVPView, I : ProductMVPInteractor> @Inject internal constructor(interator: I, schedulerProvider: SchedulerProvider, compositeDisposable: CompositeDisposable) : BasePresenter<V, I>(interactor = interator, schedulerProvider = schedulerProvider, compositeDisposable = compositeDisposable), ProductMVPPresenter<V, I> {
override fun onViewPrepared(pageNumber: Long?, categoryIds: String?) {

    getView()?.showProgress()
    interactor?.let {
        val pagingAndSortingInfo = PagingAndSortingInfo(AppConstants.PAGE_SIZE.toLong(),
                pageNumber,
                0,
                true,
                true,
                "DisplayOrder",
                AppConstants.SortDirection.Ascending.type)
        var disposable = it.getProductList(pagingAndSortingInfo, "", categoryIds.toString())
                .compose(schedulerProvider.ioToMainObservableScheduler())
                .subscribe ({ productResponse ->
                    getView()?.let {
                        it.hideProgress();
                        var totalRecords: Long? = 0;
                        var currentPage: Long? = 0;
                        var isPagingRequired: Boolean? = false;
                        totalRecords = productResponse.pagingAndSortingInfo!!.totalRecord;
                        currentPage = productResponse.pagingAndSortingInfo!!.pageNumber;
                        isPagingRequired = productResponse.pagingAndSortingInfo!!.isPagingRequired;
                        it.displayProductList(productResponse.productItems, totalRecords, currentPage, isPagingRequired);
                    }
                },{
                    t: Throwable? ->  getView()?.let {
                    it.hideProgress()
                    it.showError(t!!.message!!)
                }
                })
        addSubscription(disposable)
    }
}
}

ProductGridFragment.kt (I'm calling presenter class like below in my product fragment onViewCreated.)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    presenter.onAttach(this)
    super.onViewCreated(view, savedInstanceState)

    srl_product.setOnRefreshListener(object : SwipeRefreshLayout.OnRefreshListener {

        override fun onRefresh() {
            productAdapter.clearData()
            setPageNumber(1);
            setCategoryIds("");
            presenter.onViewPrepared(getPageNumber(), getCategoryIds());
            srl_product.isRefreshing = false;
        }

    })
}

performProductListApiCall Function (This function called in Interactor class)
override fun performProductListApiCall(request: PagingAndSortingInfo?, searchBy: String?, categoryIds: String?): Observable<ProductResponse> =
        Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PRODUCT_GETLIST)
                .addHeaders("Authorization", "bearer " + prefHelper.getAccessToken())
                .addQueryParameter("searchBy", searchBy)
                .addQueryParameter("categoryIds", categoryIds)
                .addBodyParameter(request)
                .setOkHttpClient(okHttpClient)
                .build()
                .getObjectObservable(ProductResponse::class.java)
                .doOnError {
                    t: Throwable -> Log.e("performProductListApiCall", t.message);
                }

A:
before   :

.setOkHttpClient(okHttpClient)

add those lines :

OkHttpClient okHttpClient= new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.MINUTES); // connect timeout
client.setReadTimeout(15, TimeUnit.MINUTES);    // socket timeout


text:
Q: TypeError: Attempted to assign to readonly property. on iOS8 Safari Hi this page on my site works fine on desktop browser, but has a weird bug on iOS8 Safari:
The index template doesn't show up, and there's a error in the console:
TypeError: Attempted to assign to readonly property.
and it points to the following line:
}), e("rsvp/promise/all", ["../utils", "exports"], function(e, t) {
    "use strict";
    var r = e.isArray, n = e.isNonThenable;
    t["default"] = function(e, t) {
        var i = this;
        return new i(function(t, a) {
            function o(e) {
                return function(r) {
                    c[e] = r, 0===--u && t(c)
                }
            }
            function s(e) {
                u = 0, a(e)
            }
            if (!r(e))
                throw new TypeError("You must pass an array to all.");
            var l, u = e.length, c = new Array(u);
            if (0 === u) // This is the line with error
                return void t(c);
            for (var h = 0; h < e.length; h++)
                l = e[h], n(l) ? (c[h] = l, 0===--u && t(c)) : i.cast(l).then(o(h), s)
        }, t)
    }
}), e("rsvp/promise/cast", ["exports"], function(e) {
    "use strict";

Is it a known bug to mobile safari, is there fix of it?

A: Maintainer of RSVP here, sorry that you ran into this issue.
Firstly, it appears you are using an older version of RSVP. I would recommend upgrading.
Unfortunately it appears this issue may be related to https://github.com/emberjs/ember.js/pull/5629 which appears to just be that JSC for non-64bit devices running iOS 8 is just broken when in 'use strict' mode. In my observations it only happens in specific situations and then only when the code in question has become optimized.
Again I am unsure if upgrading will help you, but you should consider it regardless. Additionally, if the problem persists removing all use strict statements may be the best option.
If no solution appears soon, I will likely publish an update to RSVP with the use strict statements removed.

A: Have you tried to remove all the  "use strict";'s from your code? From my understanding it only seems to occur with 3. generation iPads.


text:
Q: Wrong return url in Yii framework I have used Yii::app()->user->returnUrl but it always redirect me to localhost/index.php. Is there any particular configuration or some pieces of code that other programs that I must write? If you have another solutions let me know it.

A: @aslingga, can you please explain what you're trying to do with returnUrl? Are you just trying to get back to where you were after logging in, or are you using it somewhere else?
This is from the Yii documentation:

Redirects the user browser to the
  login page. Before the redirection,
  the current URL (if it's not an AJAX
  url) will be kept in returnUrl so that
  the user browser may be redirected
  back to the current page after
  successful login. Make sure you set
  loginUrl so that the user browser can
  be redirected to the specified login
  URL after calling this method. After
  calling this method, the current
  request processing will be terminated.

In other words, if the page you're trying to request requires authentication, the URI of the page you're on gets stored in a session variable. Then, once you've logged in, it takes you back to that page.
One way I'd recommend troubleshooting is to do a print_r($_SESSION); just to make sure the returnUrl is actually being stored. Then you'll be able to check if index.php is being stored as returnUrl or if you're just being redirected there for some reason.
Looking at the CWebUser methods getState and setState might also be helpful.

A: I know this question is old but maybe this will help someone out since I didn't couldn't find a decent answer anywhere.
How getReturnUrl works
Setting a default return URL for your Yii app requires a bit of customization. The way it works out of the box is that you specify the default return URL each time you call it:
Yii::app()->user->getReturnUrl('site/internal');

The idea being that if a user were to visit a page that requires authentication, they will get redirected to the login page, but not before the site running
Yii::app()->user->setReturnUrl('site/visitedpage');

Now when the user logs in, they will be returned to the page they intended to go to.
While I like that functionality, having to set the default return URL each time is dumb. If you want to change the default return URL, you have to go find it throughout your code. I suppose you could set the value in a site parameter and call
Yii::app()->user->getReturnUrl(Yii::app()->params['defaultReturnUrl']);

I don't think I have to explain why that solution is annoying too.
My Solution
So when getReturnUrl is called without any parameters, it returns either '/index.php' or just '/'. This is fine in some cases, but not always. This is better IMO.
First, extend the CWebUser class and add the following extras
class WebUser extends CWebUser {
    // default return URL property
    public defaultReturnUrl;

    // override the getReturnUrl method
    public function getReturnUrl($defaultUrl=NULL) {
        if ($defaultUrl === NULL) {
            $defaultReturnUrl = $this->defaultReturnUrl;
        }
        else {
            $defaultReturnUrl = CHtml::normalizeUrl($defaultUrl);
        }
        return $this->getState('__returnUrl',$defaultReturnUrl);
    }
}

Now, let's add a couple items to the user component array.
'user' => array(
    'class' => 'WebUser',
    'defaultReturnUrl' => 'site/internal'
)

Not only does this allow you to set a default return URL in the config, but also maintains the ability to set a different default return URL and use the setReturnUrl functionality.

A: I think, you must set it:
Yii::app()->user->setReturnUrl('controller/action');


text:
Q: Increment with bash I'm stuck trying to increment a variable in an .xml file. The tag may be in a file 100 times or just twice. I am trying to add a value that will increment the amount several times. I have included some sample code I am working on, but when I run the script it will only place a one and not increment further. Advice would be great on what I'm doing wrong.
for xmlfile in $(find $DIRECTORY -type f -name \*.xml); do
  TFILE="/tmp/$directoryname.$$"
  FROM='><process>'
  TO=' value\=""><process>'
  i=0
  while [ $i -lt 10 ]; do
    i=`expr $i + 1`
    FROM='value\=""'
    TO='value\="'$i'"'
  done
  sed "s/$FROM/$TO/g" "$xmlfile" > $TFILE && mv $TFILE "$xmlfile"
done

The while loop was something I just placed to test the code. It will insert the <process> but it will not insert the increment.
My end goal:
<process>value="1"</process>
<process>value="2"</process>
<process>value="3"</process>
<process>value="4"</process>

And so on as long as <process> is present in the file it needs to increment.

A: I just tested your code and it seems to correctly increment i.
You could try changing your increment syntax from:
i=`expr $i + 1`

To
i=$((i+1))

A: This also works.
Declaring the variable as an integer.
declare -i i=0

Then later you can increment like so:
i+=1

A: For a proper increment in bash, use a for loop (C style) :
n=10
for ((i=1; i<=n; i++)) {
    printf '<process>value="%d"</process>\n' $i
}

OUTPUT
<process>value="1"</process>
<process>value="2"</process>
<process>value="3"</process>
<process>value="4"</process>
<process>value="5"</process>
<process>value="6"</process>
<process>value="7"</process>
<process>value="8"</process>
<process>value="9"</process>
<process>value="10"</process>

NOTE
expr is a program used in ancient shell code to do math. In Posix shells like bash, use $(( expression )). In bash and ksh93, you can also use (( expression )) or let expression if you don't need to use the result in an expansion.
EDIT
If I misunderstood your needs and you have a file with blank values like this :
<process>value=""</process>

try this :
$ perl -i -pe '$c++; s/<process>value=""/<process>value"$c"/g' file.xml
<process>value"1"</process>
<process>value"2"</process>
<process>value"3"</process>
<process>value"4"</process>
<process>value"5"</process>
<process>value"6"</process>
<process>value"7"</process>

-i switch edit the file for real, so take care.

A: This is the simplest way to increment a variable in bash:
i=0
((i++))

A: Use awk:
awk '{gsub( "value=\"\"", "value=" i++ ); print }' i=1 input-file

This will replace the string value="" with value="1", value="2", etc.  You can easily change the start value and the increment ( eg ..."value=" i ); i+=5; print )


text:
Q: How do I restore backup from timeshift from external usb device I know that it is really easy to restore from previous timeshift backup on the same machine, but I have my backup files on an external hard-drive and I wonder how to restore my system directly from the backup files on that external hard drive?
It was advertised that Timeshift can help restore backups even when the system is broken (using a live CD), but Timeshift itself didn't give an example or tutorial regarding how that could be done. Any suggestions?

A: Depending on what you mean by "Broken."  If you have messed up your OS, and the system will not boot, Timeshift should work, if you have a damaged Hard Drive, probably not, because the files are on the existing hard drive.
Procedure to restore a messed up system:
Boot from the live CD
Open the Menu from the main screen, Timeshift should be under Administration.  It is accessible from the live boot.
Select Timeshift and restore your selected backup.


text:
Q: Can dark matter be ordinary matter in a quantum coherent state? The hypothetical dark matter halo envelopping a galaxy looks like to a gaussian distribution of position probability density of a particle in a quantum coherent state.
How long should a wave function of this size take to collapse according to decoherence theory?
Then, can dark matter be ordinary matter in a quantum coherent state?

A: Contrary to what you seem to assume the spatial coherence is damped by interaction with environment the faster the longer distances you consider.
Following this paper if we couple the particle to the thermal bath of photons the relevant density matrix element goes like,
\begin{equation}
\rho(\vec{x},\vec{y},t)\simeq \rho(\vec{x},\vec{y},t_0) e^{-\Delta |\vec{y}-\vec{x}|^2(t-t_0)/2},
\end{equation}
where $\Delta$ is a decoherence rate depending on the effective cross-section and the temperature of the bath.
For electrons interacting with just cosmological background radiation gives $\Delta\sim 10^{-10} cm^{-2} s^{-1}$. For $|\vec{y}-\vec{x}|\sim 10^5$ light years it gives characteristic time (in which the matrix element divides itself by $e$) of just $\sim 10^{-36} s$. And that's just from the cosmological background not taking into account all the stuff happening in galaxies which leaves no hope for your idea even in case of the neutral particles.

A: If we ignore GR, the answer is no, by using the decoherence time formula (19) of Zurek's paper p13, depending on the thermal de Broglie wavelength.


text:
Q: Deleting records in sales cloud using REST api I am trying to delete multiple records using REST Api.
    var contentType = 'application/json; charset=utf-8';
    var headerNames = ["Authorization"];
    var headerValues = [("Bearer "+sessionId)];

    var allRecords = DataExtension.Init("MyDataExtension").Rows.Retrieve();
    for (var i=0; i < allRecords.length; i++){
          var ContactId = allRecords[i].ContactId;
          var Url = ('https://blablabla.my.salesforce.com/services/data/v42.0/sobjects/Contact/' + ContactId);

          var result = HTTP.Delete(Url, contentType, headerNames, headerValues);
        }

However, I am getting this error:

Jint.Native.JsException: Object expected: Delete.

What is wrong with this ssjs code? or is there any other way to do this?
EDIT
Below is my edited code. This returns error:

The remote server returned an error: (400) Bad Request.

var contentType = 'application/json; charset=utf-8';
var headerNames = ["Authorization"];
var headerValues = [("Bearer "+sessionId)];

var allRecords = DataExtension.Init("MyDataExtension").Rows.Retrieve();

var url = 'https://blablabla.my.salesforce.com/services/data/v42.0/composite';
var payload = { "compositeRequest": [] };

for(var i = 0; i < allRecords.length; i++) {
//var contact = Stringify(allRecords[i].ContactId);
payload.compositeRequest.push(
    { "method": "DELETE",
    "url": "/services/data/v42.0/sobjects/Contact/"+allRecords[i].ContactId   //allRecords[i].ContactId OR var contact?
    });
if(payload.compositeRequest.length == 25 || i == allRecords.length - 1) {
    var response = HTTP.Post(url, "application/json", Stringify(payload), headerNames, headerValues);  // JSON.Stringify OR Stringify?
    log.Rows.Add({Log: "response: " + response});
    payload.compositeRequest = [];
    }
}

A: HTTP.Delete is not a valid method name. You only have the options for GET and POST. Instead, use the POST method and use the composite request resource. As a bonus, you can delete up to 25 records at once this way.

var url = 'https://blablabla.my.salesforce.com/services/data/v42.0/composite';
var payload = { "compositeRequest": [] };
for(var i = 0; i < allRecords.length; i++) {
  payload.compositeRequest.push(
    { "method": "DELETE",
      "url": "/services/data/v42.0/sobjects/Contact/"+allRecords[i].ContactId
    });
  if(payload.compositeRequest.length == 25 || i == allRecords.length - 1) {
    var response = HTTP.Post(url, "application/json", Platform.Function.Stringify(payload), headerNames, headerValues);
    payload.compositeRequest = [];
  }
}


text:
Q: UIView animations not working Somehow something in my code is disabling animations, and I cannot find it. I built a search bar in my app, it has a delegate call for begin and end editing. When it begins I have a animation block to change its size, and it works, but the animation when it ends does not. I have commented out EVERY line of code except for the animations and the delegate calls, and even set delays on the animation blocks and it is always set instantly, but interaction with the objects is delayed for the amount of time of the animation. Is there a reason why the animation is being disabled or a general way to figure out why the animations are skipping?
EDIT: Even disabling all the code for the delegates and having a animation block with a delay isn't working, the button is tapped and calls
- (void)cancelButtonPressed:(id)sender {
    [UIView animateWithDuration:5.0f delay:5.0f options:0 animations:^{
        self.layer.borderWidth = 1.0f;
        self.layer.borderColor = [UIColor redColor].CGColor;

    } completion:^(BOOL finished) {

    }];
}

which happens instantly, doesn't even delay for 5 seconds.
EDIT 2: I put the animation code in another block that can perform the code inside after a delay, the code does correctly delay but the animation still doesn't work.
Edit 3: Here is the code for the button that calls the cancelButtonPressed method.
cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
            [cancelButton setTitle:NSLocalizedString(@"Cancel", @"Cancel") forState:UIControlStateNormal];
            cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
            [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cancelButton];

Edit 4:
Here is a video of the animation issue. When I click the cancel button it is instantly shrunk, but the code is in an animation block that is supposed to take 5 seconds, here is the video and code.
Video: http://cl.ly/3x3k3H2m1Y2F
barItem is a UIBarButton item, its customView is my search bar UIView subclass.
[UIView animateWithDuration:5.0f animations:^{
                barItem.width = 200;
                CGRect addressBarFrame = barItem.customView.frame;
                addressBarFrame.size.width = 200;
                barItem.customView.frame = addressBarFrame;
            } completion:^(BOOL finished) {
                NSLog(@"COMPLETION!");
            }];

Edit 5:
What Im really trying to do: The app I am working on is a web browser. I built a custom search bar view. The view is in a UIBarButtonItem that is inside a UIToolbar attached to the top of the screen. When the user taps inside the bar item, the text field becomes active and the keyboard displays, the frame of a view inside is animated to shrink and a cancel button appears (still part of this search bar UIView subclass). When the cancel button is tapped it calls a method inside the subclass, and that does some clean up, then calls its delegate method to my UIViewController, which will then animate the frame again to get bigger. The reason why I need to change the frame is because if the text field gets too small I need to make it bigger while editing, but then can make it smaller when editing is done.
The issue: When the text field becomes active, the frame is changed inside an animation block. The frame properly animates over the amount of time given and to the new set frame. When the cancel button is tapped, another animation block gets called to change the frame again, but no matter if this animation block is in the delegate method or in the UIView subclass, or whatever I try to animate, will NOT be animated. If I add a delay onto the animation block, it will still act as if the code was called outside of a animation block, although the completion block is called at the right time, and if I put the animation block inside a block that can delay the code it will properly be delayed but the animation still does not happen. Taps also do not affect the view until the animation time is done, like normal.
Edit 7: If i animate the cancelButtons frame, or background color It will work. So I thought maybe its an issue with the toolbar that it is in, but animating the background color of that also works. So I still have no idea why I can animate the frame of the bar item and the custom view (the custom view in the code above) before editing but cannot animate it after editing.
Edit 8: I have figured out the issue.
It was an optical illusion the entire time. Even though setting the UIBarButtonItem's width inside a animation block, the surrounding bar items would automatically space out to the new frame. And even though the frame is really animating, the subviews are automatically in their correct place, but the sequence of the animation made it look like it really was animating everything correctly. The animation I was trying to do when editing was finished was more noticeable so I thought only that was not animating. Changing around some stuff makes it look better but I don't think its possible to have the bar button items to animate the way I want.

A: Revised
If your trying to commit animations when a programmatically induced search bar is canceled then something like this will do the trick:
@interface TableViewController : UITableViewController <UISearchBarDelegate>

@property (strong, nonatomic) UISearchBar *searchBar;

@end

- (void) viewDidLoad:(BOOL)animated {

UIView *searchbarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 44)]; //This adds a container that will hold the search bar.
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 40, 44)];
self.searchBar.showsCancelButton = YES;
[searchbarView addSubview:self.searchBar];
self.searchBar.delegate = self;
[self.view addSubview:searchbarView]; or add to whatever view you want.
}

This is where you might be going wrong:
When a search bar is canceled you have to have the method searchBarCancelButtonClicked: invoked:
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[self animateButton];
}

-(void)animateButton {
//Commit your animations here:
}

A: Try this
[UIView animateWithDuration:5.0 animations:^{
        CGRect addressBarFrame = barItem.customView.frame;
        addressBarFrame.size.width = 200;
        barItem.customView.frame = addressBarFrame;
    } completion:^(BOOL finished) {
        NSLog(@"COMPLETION!");
    }];

or  this
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:5.0];
CGRect addressBarFrame = barItem.customView.frame;
addressBarFrame.size.width = 200;
barItem.customView.frame = addressBarFrame;
[UIView commitAnimations];

A: Have you write [UIView setAnimationsEnabled:NO];
Check in your code. Sometimes it creates problem with UIView animation.


text:
Q: Notification still in bar after killing Service I have interesting issue:
I start my Activity and from this Activity I start my Service in another process.
When the Service is started it shows a notification in the bar.
Notification is with .setOngoing(true), so it will only dissapear only when I stop the Service from my Activity.
Then in Eclipse, in tab Devices I kill my Service-process, but the notification is still exists!
To close it I have to start the Service again and then have to stop it.

Why is my Notification not killed together with Service?

A: So you said that the service is on another process?
Im developing an app with a similar structure. Please Check out the "AbstractService" class and the "ServiceManager" class from package com.philippheckel.service.
Here are the classes
Here an Example
So here is how i create the notification
Use the Compat.Builder for Compatibility with older and newer android versions
NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle(getResources().getString(R.string.service_header))
        .setContentText("Connect to: http://" + httpd.getip() + ":8080")
        .setContentIntent(pendingIntent)
        .setOngoing(true);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(01, mBuilder.build());

So here is how i close/cancel the notification
See that im using the same ID again? this is very important
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(01);

A: R u clearing the notifications at the time of stoping the service
If not clear the notification
just have a look into NotificationManager class to how to clear.
http://developer.android.com/reference/android/app/NotificationManager.html


text:
Q: Write xml with c#? I create a form so I use textbox and I would like when I push the button "send" he filled xml :
for exemple 1 time :
<?xml version="1.0" encoding="utf-8"?>
<DonneesLocale>
  <Donnee>
    <id>1</id>
    <libelle>bla </libelle>
    <email_asso>bla@</email_asso>
    <login>bla</login>
    <psw>bla</psw>
    <site>bla</site>
    <description>bla</description>
    <data_1_lib></data_1_lib>
    <data_1_val></data_1_val>
    <data_2_lib></data_2_lib>
    <data_2_val></data_2_val>
  </Donnee>
</DonneesLocale>

and 2nd time when I push the button:
    <?xml version="1.0" encoding="utf-8"?>
<DonneesLocale>
  <Donnee>
    <id>1</id>
    <libelle>bla </libelle>
    <email_asso>bla@</email_asso>
    <login>bla</login>
    <psw>bla</psw>
    <site>bla</site>
    <description>bla</description>
    <data_1_lib></data_1_lib>
    <data_1_val></data_1_val>
    <data_2_lib></data_2_lib>
    <data_2_val></data_2_val>
  </Donnee>
<DonneesLocale>
  <Donnee>
    <id>2</id>
    <libelle>hello</libelle>
    <email_asso>hello@</email_asso>
    <login>hello</login>
    <psw>hello</psw>
    <site>hello</site>
    <description>hello</description>
    <data_1_lib></data_1_lib>
    <data_1_val></data_1_val>
    <data_2_lib></data_2_lib>
    <data_2_val></data_2_val>
  </Donnee>
</DonneesLocale>

Someone can help me please ?
(Sorry for my English !)
Thanks !

A: So if I get it correct, you want to append new data to your existing xml.
For that you can chose to temporarily store the current xml and and add new data to it using Linq Xml.
To do this, now you need to modify your current code with an additional check for xml file exists before all calls to press button event. The code for appending to xml can be found Appending an existing XML file with XmlWriter

A: If you are using a list of objects then you can update the list on button click and parse your object list in xml like below:
var xml = new XElement("DonneesLocales", DonneesLocalList.Select(x => new XElement("DonneesLocale",
                   new XElement("Donnee",
                   new XElement("id"),
                   new XElement("libelle"),
                   new XElement("email_asso"),
                   new XElement("login"),
                   new XElement("psw"),
                   new XElement("site"),
                   new XElement("description"),
                   new XElement("data_1_lib"),
                   new XElement("data_1_val"),
                   new XElement("data_2_lib"),
                   new XElement("data_2_val")))));

A: Another option is their for XML Serialization and Deserialization which will be done with the help of XMLSerializer,
public class DonneesLocale
    {
        private List<Donnee> donnee = new List<Donnee>();

        [XmlArray("DonneesLocale")]
        public List<Donnee> Donnee
        {
            get { return donnee; }
            set { donnee = value; }
        }
    }

    [XmlType("Donnee")]
    public class Donnee
    {
        [XmlElement("id")]
        public int id { get; set; }

        [XmlElement("libelle")]
        public string libelle { get; set; }

        [XmlElement("email_asso")]
        public string email_asso { get; set; }

        [XmlElement("login")]
        public string login { get; set; }

        [XmlElement("psw")]
        public string psw { get; set; }

        [XmlElement("site")]
        public string site { get; set; }

        [XmlElement("description")]
        public string description { get; set; }

        [XmlElement("data_1_lib")]
        public string data_1_lib { get; set; }

        [XmlElement("data_1_val")]
        public string data_1_val { get; set; }

        [XmlElement("data_2_lib")]
        public string data_2_lib { get; set; }

        [XmlElement("data_2_val")]
        public string data_2_val { get; set; }
    }

DonneesLocale dnl = new DonneesLocale();

        private void Serialize(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                var temp = new Donnee() { id = i, libelle = "libelle " + i, email_asso = "email_asso " + i, login = "login " + i, psw = "psw " + i, site = "site " + i, description = "description " + i, data_1_lib = "data_1_lib " + i, data_1_val = "data_1_val " + i, data_2_lib = "data_2_lib " + i, data_2_val = "data_2_val " + i };
                dnl.Donnee.Add(temp);
            }

            try
            {
                // to Save columnorders to the file
                var serializer = new XmlSerializer(typeof(DonneesLocale));
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                using (TextWriter writer = new StreamWriter(@"Your XML Path"))
                {
                    serializer.Serialize(writer, dnl, ns);
                }

            }
            catch { }
        }

        private void Deserialize(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(@"Your XML Path"))
                {

                    var deserializer = new XmlSerializer(typeof(DonneesLocale));
                    using (TextReader reader = new StreamReader(@"Your XML Path"))
                    {
                        dnl = (DonneesLocale)deserializer.Deserialize(reader);
                    }

                }
            }
            catch
            {
            }
        }

all you need is to add an object to the list and serialize the object to XML whenever you want,
this will work as you expected,


text:
Q: profilePic.move is not a function [AdonisJS] I am facing the error while trying to upload a file(image) via the form on AdonisJS (I referred to the official docs @AdonisJS4.1 File Uploads)
await profilePic.move(Helpers.tmpPath('uploads'), {
    name: 'custom.jpg',
    overwrite: true
})

if (!profilePic.moved()) {
    console.log('file not moved')
}

A: Official Docs Here
HTML
<form method="POST" action="upload" enctype="multipart/form-data">
  <input type="file" name="profile_pic" />
  <button type="submit"> Submit </button>
</form>

JS
const Helpers = use('Helpers')

Route.post('upload', async ({ request }) => {
  const profilePic = request.file('profile_pic', {
    types: ['image'],
    size: '2mb'
  })

  await profilePic.move(Helpers.tmpPath('uploads'), {
    name: 'custom-name.jpg',
    overwrite: true
  })

  if (!profilePic.moved()) {
    return profilePic.error()
  }
  return 'File moved'
})


text:
Q: Missing distances when using igraph shortest distance I am trying to calculate the distance between the nodes of my network and two sources. Afterwards I the save the shortest distance in a list (called route_length). However my network has 9693 nodes and after running my code and calculating the shortest paths I only have
9602 distances. I don't understand why I have less distances than nodes, plus if in the loop I save the nodes in a list and print it's length at the end it too gives me a result of 9602 nodes, which is not correct.
Here is my code:
import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
import igraph as ig
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')

G_nx = nx.relabel.convert_node_labels_to_integers(G)

ox.speed.add_edge_speeds(G_nx, hwy_speeds=20, fallback=20)

ox.speed.add_edge_travel_times(G_nx)

weight = 'travel_time'

coord_1 = (38.74817825481225, -9.160815118526642)  # Coordenada Hospital Santa Maria
coord_2 = (38.74110711410615, -9.152159572392323)  # Coordenada Hopstial Curry Cabral
coord_3 = (38.7287248180068, -9.139114834357233) # Hospital Dona Estefania
coord_4 = (38.71814053423293, -9.137885476529883) # Hospital Sao Jose
target_1 = ox.get_nearest_node(G_nx, coord_1)
target_2 = ox.get_nearest_node(G_nx, coord_2)
target_3 = ox.get_nearest_node(G_nx, coord_3)
target_4 = ox.get_nearest_node(G_nx, coord_4)

G_ig = ig.Graph(directed=True)
G_ig.add_vertices(list(G_nx.nodes()))
G_ig.add_edges(list(G_nx.edges()))
G_ig.vs['osmid'] = list(nx.get_node_attributes(G_nx, 'osmid').values())
G_ig.es[weight] = list(nx.get_edge_attributes(G_nx, weight).values())

assert len(G_nx.nodes()) == G_ig.vcount()
assert len(G_nx.edges()) == G_ig.ecount()

route_length=[]
list_nodes=[]

for node in G_nx.nodes:
    length_1 = G_ig.shortest_paths(source=node, target=target_1, weights=weight)[0][0]
    length_2 = G_ig.shortest_paths(source=node, target=target_2, weights=weight)[0][0]

    if length_1<length_2:
       route_length.append(length_1)
       list_nodes.append(node)

   elif length_2 < length_1:
       route_length.append(length_2)
       list_nodes.append(node)

print(len(route_length))
print(len(list_nodes))

If the nodes are disconnected the shortest path should be inf. And I don't have any inf values in the route_length list.
Thank you in advance.

A: The first thing that popped into my mind was what about the case when
length_1 == length_2?
I believe that is the condition that is satisfied (and hence not accounted for by the if and elif and not appended in the list route_length and list list_nodes) for the missing 91 cases.


text:
Q: How to present UIViewController on top of current view controller with smaller height I would like to present a UIViewController on top of the current view controller and set it's height to ~80% of the screen size. I've got the first part:
let additionalVC = ChartsViewController(currentSelection)
additionalVC = .overCurrentContext
present(additionalVC, animated: true)

I tried setting the self.view.frame inside my ChartsVC in viewDidLoad and couple of different things but it is always presented in the full screen mode.
That's what I want to achieve:

*

*blueVC - currentVC

*redVC - ChartsVC - VC on top of the current VC with ~80% of the original height

btw I'm doing everything programmatically, no xib and UIStoryboard.

A: There's a number of ways to achieve this.
You could use a 3rd party framework (http://transitiontreasury.com/) or the way I would do this.
Present the newVC where a transition = model over current context
ensure the newVC.views background color is clear
add another view where origin.y is the distance between the top and the desired gap. This is the view where all your objects will sit on.
If you need a coding example let me know, but its a pretty simple solution and looking at your code your 80% there.
Thomas

A: Implement a custom UIPresentationController.  To use a custom view size, you only need to override a single property.
This code will simply inset the presented view controller by 50x100 pts:
class MyPresentationController: UIPresentationController {

    // Inset by 50 x 100
    override var frameOfPresentedViewInContainerView: CGRect {
        return self.presentingViewController.view.bounds.insetBy(dx: 50, dy: 100)
    }

}

To darken the presenting view controller, override presentationTransitionWillBegin() and dismissalTransitionWillBegin() to insert a shading view and animate it into view:
class MyPresentationController: UIPresentationController {

    override var frameOfPresentedViewInContainerView: CGRect {
        return self.presentingViewController.view.bounds.insetBy(dx: 50, dy: 100)
    }

    let shadeView = UIView()

    override func presentationTransitionWillBegin() {
        self.shadeView.backgroundColor = UIColor.black
        self.shadeView.alpha = 0

        // Insert the shade view above the presenting view controller
        self.shadeView.frame = self.presentingViewController.view.frame
        self.containerView?.insertSubview(shadeView,
            aboveSubview: self.presentingViewController.view)

        // Animate it into view
        self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in
            self.shadeView.alpha = 0.3
        }, completion: nil)
    }

    override func dismissalTransitionWillBegin() {
        self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in
            self.shadeView.alpha = 0.0
        }, completion: nil)
    }
}

To use your custom presentation controller, set the modalPresentationStyle and transitioningDelegate:
class MyViewController : UIViewController, UIViewControllerTransitioningDelegate {

  //
  // Your code
  //
  func presentCharts() {
    let additionalVC = ChartsViewController(currentSelection)
    additionalVC.modalPresentationStyle = .custom
    additionalVC.transitioningDelegate = self
    self.present(additionalVC, animated: true)
  }

  //
  // UIViewControllerTransitioningDelegate protocol
  //
  func presentationController(forPresented presented: UIViewController,
                              presenting: UIViewController?,
                              source: UIViewController) -> UIPresentationController? {

    return MyPresentationController(presentedViewController: presented,
                                    presenting: presenting)

  }
}

A: In IOS 13 and Xcode 11, you can present ViewController with modalPresentationStyle = .automatic

A: Take Two ViewController.First view controller have a button and the button action name is clicked.The target is to clicking the button we want to add secondVC as a child of first view controller and show secondVC 80% of the first view controller.again click button we remove secondVC from first view controller. below is the code for click button action.
@IBAction func clicked(_ sender: UIButton) {

    if !isshown{
        isshown = true

        self.addChildViewController(vc)
        self.view.addSubview(vc.view)
        vc.didMove(toParentViewController: self)
        let height = view.frame.height
        let width  = view.frame.width
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.vc.view.frame = CGRect(x: 0, y: 100 , width: width, height: height - 100)
        }, completion: { (result) in
            // do what you want to do
        })

    }else{
        isshown = false
        UIView.animate(withDuration: 0.3,
                       delay: 0,
                       options: UIViewAnimationOptions.curveEaseIn,
                       animations: { () -> Void in
                        var frame = self.vc.view.frame
                        frame.origin.y = UIScreen.main.bounds.maxY
                        self.vc.view.frame = frame

        }, completion: { (finished) -> Void in
            self.vc.view.removeFromSuperview()
            self.vc.removeFromParentViewController()
        })
    }

}

here vc is a reference of secondVC.
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Second") as! secondVC

change below piece of code to get whatever percentage you want.
self.vc.view.frame = CGRect(x: 0, y: 100 , width: width, height: height - 100)


text:
Q: How to run a webtest from vnext including Context Parameter I am trying to create a smoke test for a webserver using a webtest and tfs build 2015. I have a webtest that uses a Datasource(n rows) to run n times. I also have a Context Parameter used to configure the test to various web urls. I used an orderedtest to contain the webtest. I can run the orderedtest using the Visual Studio Test Task. Unfortunately, I needed to create multiple file copies of each webtest and orderedtest because I cannot figure out how to pass a Context Parameter to an orderedtest/webtest.

A: Environment variables whose name starts Test. are added to the web test as context parameters. If environment variable Test.Abcd has the value efgh then the context parameter Abcd will to be set to efgh. See here for more details.


text: Q: How to disable Windows built-in keyboard using command Is there a way i can disable the Windows built-in keyboard via Terminal Preview, Just like how i can accomplish the same thing on Ubuntu with thee command xinput disable <key> ?


text:
Q: Creating multiple ZIP files based on a size limit
Possible Duplicate:
Compress a folder into multiple zip files

Say I've got a folder 10 GB in size. I want to compress it into zip files of no more than 500 MB each, as many zip files as that takes.
Is there an easy way to do this without writing my own script?

A: If you are looking for a utility that will create individually decompressible zip files of no more than 500MB I guess you need to write your own script.
However, if you are looking for a utility that will create a 'volume set' of zip/rar/etc file of a certain size e.g. 500MB then you can consider p7zip (http://sourceforge.net/projects/p7zip/, available for mac)
Good luck!

A: Can you use winrar or splitter and merger, or are you restricted to winzip?
Have a look at http://www.astahost.com/info.php/how-compress-one-file-into-several-parts_t3927.html.
Personally, I use winrar and it works great.
EDIT: Just realised you are on OSX, try this maybe: http://homepage.mac.com/pnoriega/unrar.html
Same principles.
j


text:
Q: React Native Sourcemaps - Wrong Files When I remote-debug in Chrome, the files are all wrong. Open a source file, and it's not the file it claims to be.
e.g....

*

*Open common/BaseComponent.js and you get the source is for
native/components/logGraph.js.

*Open
native/components/logGraph.js and you get the source for
native/actions/driverActions.js.

*And so on, no apparent rhyme or reason.

Even when I find the "right" file, breakpoints are not hit.
Then...switch to some certain older branch, the problem is goes away. This tells me there's something specific in my code that react-native is tripping over.
I'm lost as to how to even troubleshoot this. If anyone else is having this problem, I can't find it on the Interwebs.
Suggestions?
In case it's relevant, we're using Genymotion for emulation. We're on react-native 0.26. My parter is working on getting us to 0.30-rc to see if that fixes it.


text:
Q: Bootstrap Modal not working with parallax features Testing the third iteration of my professional website
I've created a bootstrap modal over a parallax feature that won't allow me to open the contact form in the modal without resorting to a transparent background. Any help fixing this is greatly appreciated! Visit my website and see for yourself, this is a tough one to figure out! PS: You're looking for the Book Now! buttons.
HTML code:

        Book Now!

            <button type="button" class="close" data-dismiss="modal">×</button>

Contact Form

Hourly Consulting Rate: $40 - $120/h

                <form id="contact-form" method="post" action="contact.php" role="form"
                data-toggle="validator">

                Firstname *
                <input id="form_name" type="text" name="name" class="form-control" placeholder="Your firstname! *" required="required" data-error="Firstname is required.">

                Lastname *
                <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Your lastname! *" required="required" data-error="Lastname is required.">

                Email *
                <input id="form_email" type="email" name="email" class="form-control" placeholder="Your email! *" required="required" data-error="Valid email is required."
                pattern="[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*">

                Phone
                <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Your phone number!">

                Message *
                <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>

            <input type="submit" class="btn btn-success btn-send" value="Send message">

* These fields are required.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    body, html {
      height: 100%;
      margin: 0;
      font: 400 15px/1.8 "Lato", sans-serif;
      color: #777;
    }

    img.headshot {
        margin-right: auto;
        margin-left: auto;
    }

    .bgimg-1, .bgimg-2, .bgimg-3 {
      position: relative;
      opacity: 0.65;
      background-attachment: fixed;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;

    }
    .bgimg-1 {
      background-image: url("images/building1.gif");
      min-height: 100%;
    }

    .bgimg-2 {
      background-image: url("images/cityscape1.gif");
      min-height: 400px;
    }

    .bgimg-3 {
      background-image: url("images/TheBay.gif");
      min-height: 400px;
    }

    .caption {
      position: absolute;
      left: 0;
      top: 50%;
      width: 100%;
      text-align: center;
      color: #000;
    }

    .caption span.border {
      background-color: #111;
      color: #fff;
      padding: 18px;
      font-size: 25px;
      letter-spacing: 10px;
    }

    h3 {
      letter-spacing: 5px;
      text-transform: uppercase;
      font: 20px "Lato", sans-serif;
      color: #111;
    }

    div.bgimg-2-still {
      background-image: url("images/building1.jpg");
      width: 100%;
      height: auto
    }

A: $(window).load($('#myModal').appendTo('body'))

will take your modal from where you placed it and append it to , where it should have been placed in the first place.

As a side note, you have several JavaScript errors on your website due to improper loading of scripts. You should have a professional look at your "professional website".


text:
Q: mpld3 plugin to set xtics I'm trying to make an mpld3 plugin so when I mouse over over a circle of the scatter plot, It shows the sin line, but with the x-axis starting where the line starts and ,ending where line ends.
Which method should I call to achieve this?
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import mpld3
from mpld3 import plugins, utils

mpld3.enable_notebook()

class LinkedView(plugins.PluginBase):
    """A simple plugin showing how multiple axes can be linked"""

    JAVASCRIPT = """
    mpld3.register_plugin("linkedview", LinkedViewPlugin);
    LinkedViewPlugin.prototype = Object.create(mpld3.Plugin.prototype);
    LinkedViewPlugin.prototype.constructor = LinkedViewPlugin;
    LinkedViewPlugin.prototype.requiredProps = ["idpts", "idline", "data"];
    LinkedViewPlugin.prototype.defaultProps = {}
    function LinkedViewPlugin(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    LinkedViewPlugin.prototype.draw = function(){
      var pts = mpld3.get_element(this.props.idpts);
      var line = mpld3.get_element(this.props.idline);
      var data = this.props.data;

      pts.elements().on("mouseover", function(d, i){

        var begin = d[0]-2;
        var end = d[0]+2;
        console.log("Show from " + begin + " to " + end);
        var truncated = Array();
        for (var row = 0; row < data[i].length ; ++row){

            var x = data[i][row][0];
            if ( begin <= x && x <= end){
                truncated.push(data[i][row]);
            }
        }

        line.data = truncated;
        line.elements().transition()
            .attr("d", line.datafunc(line.data))
            .style("stroke", this.style.fill);

      });
    };
    """

    def __init__(self, points, line, linedata):
        if isinstance(points, matplotlib.lines.Line2D):
            suffix = "pts"
        else:
            suffix = None

        self.dict_ = {"type": "linkedview",
                      "idpts": utils.get_id(points, suffix),
                      "idline": utils.get_id(line),
                      "data": linedata}

fig, ax = plt.subplots(2)

# scatter periods and amplitudes
np.random.seed(0)
P =np.random.random(size=20)*10
A = np.random.random(size=20)
x = np.linspace(0, 10, 100)
data = np.array([[x, Ai * np.sin(x / (Pi/10))]

for (Ai, Pi) in zip(A, P)])
points = ax[1].scatter(P, A, c=(P/10 + A),s=200, alpha=0.5)
ax[1].set_xlabel('Period')
ax[1].set_ylabel('Amplitude')

# create the line object
lines = ax[0].plot(x, 0 * x, '-w', lw=3, alpha=0.5)
ax[0].set_ylim(-1, 1)

ax[0].set_title("Hover over points to see lines")

# transpose line data and add plugin
linedata = data.transpose(0, 2, 1).tolist()
plugins.connect(fig, LinkedView(points, lines[0], linedata))

mpld3.display()

A: There is a javascript function in mpld3.js called set_axlim. In your javascript code, you'll want to call pts.ax.set_axlim with the limits you'd like to set. Here is an example of where the method is called.


text:
Q: load XML doesnt like large xml file So I've got some code which grabs an XML file from a 3rd party URL and stores it locally.
    function get_file($file, $local_path, $newfilename) {
        echo "
Attempting message download for $file
";
        $out = fopen($local_path.$newfilename,"wb");
        if ($out == FALSE){
              print "File not opened
";
              exit;
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_FILE, $out);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $file);

        curl_exec($ch);
        echo "
Error is : ".curl_error ( $ch);

        curl_close($ch);

    }
    get_file('URL FOR FILE', '../xml/', 'jobs.xml');

This works great - I can download the XML file and see it in my xml folder - its about 350mb.
I then try to load it to my database like so:
$mysqli = new mysqli(CONNECTION DETAILS);

$sql = "LOAD XML LOCAL INFILE '../xml/jobs.xml' REPLACE INTO TABLE jobs ROWS IDENTIFIED BY '<job>'";

// check connection
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

// Run the query
$mysqli->query($sql);

// Close the connection
$mysqli->close();

This part doesnt work...
The thing is, it works fine with a smaller XML test file.
Should LOAD XML be capable of processing a 350mb XML? If so, why isnt this code working?
If 350mb is too big, what can I do to get the xml data into my database (in columns etc). the XML file has about 130,000 entries.

A: I'd expect mysql/mariadb to be able to process big data (bigger than memory) using a streaming approach. But I'd not expect it to eat whatever data format.
So there is a chance you have to translate the XML first, or you could even write your own application that uses a streaming parser to read the file and then run the appropriate SQL statements on your database.


text:
Q: Why are there so many feature-request with no official response? There are lots of questions tagged feature-request that don't have a status-* response.
How do we interpret this?
Is it because they are declined by default?
We just have to wait for a response (the team is very busy)? Is Jeff the only one that reviews this questions?
I suppose the ones that have negative votes may (or may not) be declined by default, but there are quite a few with some to a lot upvotes that should have an official answer.

A: As Jeremy notes it is, sadly, kind of a lose-lose proposition to follow up on every single feature req.
As always,please vote up feature requests you agree with! I assure you that I regularly look at the highest voted bugs and feature requests which are not tagged with a [status-*]. Anything with a lot of votes is much more likely to be acted upon... So convince you fellow meta users that your request has merit, first!

A: I work in another publicly accessible community, where bug reports and feature requests are happily solicited from the userbase.
We have thousands of open idea requests (the codebase is nearing 20 years old), and close only a sizeable fraction of those opened regularly.
From our perspective, the idea requests are welcome, but not all of them are actionable; some are brilliant, and are implemented immediately because they work well with our vision; some are entirely incompatible and are closed/denied.
The majority fit in between; they're ideas that would work with a bit of tweaking, or a bit of thought, but aren't necessarily on the primary development roadmap, so don't get our attention immediately. Nor do they warrant closing, because they are relevant, merely not timely or important.
Because our developers have their own ideas, their own neverending todo lists, we treat the open idea pile more as inspiration than as a roadmap. There's very much a feeling of "we'll get to it when we've run out of other things to do", but this never happens in practice.
Not to speak for Jeff and the others, but I think it's a normal thing to have to choose between two equally bad things in a public forum like this: either responding to most feature requests with a "denied", and so risk upsetting the folk who love the community enough to contribute with their own ideas; or leave some of them dangling because they're not immediately and obviously wrong, but to do something worthwhile with them takes more time and effort than the idea deserves right now.


text:
Q: How to save Spring form data using jquery ajax without refreshing page? i try out this example... where student class object is getting at controller side. and we can use it directly. but here the page is getting submitted.
here i want it call the post method using jquery ajax and post data as class object. instead of sending each input field value.
how can i achieve this?
for example i want to send post request to this controller
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("SpringWeb")Student student,
   ModelMap model) {
      //here will be my code to use student object....

      return "result";
   }

using this Spring form..
<form:form method="POST" action="/HelloWeb/addStudent">

        <form:label path="name">Name</form:label>
        <form:input path="name" />

        <form:label path="age">Age</form:label>
        <form:input path="age" />

        <form:label path="id">id</form:label>
        <form:input path="id" />

            <input type="submit" value="Submit"/>

</form:form>

A: I am going to answer with an existing question.. jQuery AJAX submit form
For Spring's model attribute mapping to work, you only have to make sure the form input names stay consistent. The best way to progressively convert your traditional form submit to an ajax style form submit is to trap the form submit event, serialize the form and make an ajax call. Since all param names and values are going to remain consistent, your backend code will work as is.
Note: You will have to handle responses differently though, since a normal form submit returns the success or error page, while with ajax you'll need something else. But since this question is about form submission, won't go into details about response handling.
Hope this answers your question.

A: You will have to convert form values to json, and use and an ajax post request to submit data to server.
I did it using the toObject plugin for jQuery. And the JSON stringify function.


text:
Q: Using shared library within shared library I want to use a shared library within a shared library but g++ is complaining...
That is how my test sample looks:
.
├── extA
│   ├── a.cpp
│   ├── a.h
│   └── libA.so
├── extB
│   ├── b.cpp
│   ├── b.h
│   └── libB.so
└── main.cpp

a.h:
#pragma once

int f(void);

a.cpp:
#include "a.h"

int f(void) {
        return 42;
}

b.h:
#pragma once

#include "a.h"

int g(void);

b.cpp:
#include "b.h"

int g(void) {
        return f();
}

main.cpp:
#include <cstdlib>
#include <iostream>

#include "b.h"

int main(int, char **) {
        std::cout << g() << std::endl;

        return EXIT_SUCCESS;
}

I pretty sure that my way of compiling is wrong. That is what I do:
g++ -c -fpic a.cpp
g++ -shared -o libA.so a.o

to create libA.so,
g++ -c -fpic -I../extA b.cpp -L../extA -lA
g++ -shared -o libB.so b.o

to create libB.so (I think this way is incorrect) and finally:
g++ -IexB main.cpp -LextB -lB -o main

The last g++-call leads to the error msg:
In file included from main.cpp:4:0:
extB/b.h:3:15: fatal error: a.h: No such file or directory
 #include "a.h"
               ^
compilation terminated.

Can someone tell me, what is the right way to compile/create libB.so?

A: main.cpp:4:15: fatal error: b.h: No such file or directory
 #include "b.h"
               ^

The error is nothing to do with libB.so it means main.cpp cannot find b.h, which is a problem finding headers, nothing to do with the shared library file.
If b.h is not in the same directory as main.cpp then you need to tell the compiler how to find the header, e.g. by using -IextB when compiling main.cpp
The file main.cpp includes the header b.h and uses the function g() defined in libB.so so why are you compiling main.cpp telling it how to find a.h and linking to libA.so? It doesn't need that header or that library!
You probably just want to change A to B since that's what main.cpp actually depends on:
g++ -IextB main.cpp -LextB -lB -o main

A: I found the solution.
The correct way to compile libB.so is:
g++ -c -fpic -I../extA b.cpp
g++ -shared -o libB.so b.o -L../extA -lA


text:
Q: Customize your XML when converting a DataTable to an XML file in C# I found out how to convert a DataTable into XML using this post - How can I convert a DataTable to an XML file in C#?
string result;
using (StringWriter sw = new StringWriter()) {
dataTable.WriteXml(sw);
result = sw.ToString();
}

In the above code, we see that each row will be enclosed with TABLE tags. Is there any way I could replace it with custom tags, like ROW ? Of course, I could search the string itself and replace TABLE with ROW, but I want a different approach.

A: you can use Linq to traverse all the rows of DataTable and build the string you want
Reading values from a DataTable column into a List<string> with LINQ
Or you can use LinqToXml to change the XML returned from WriteXml method
Linq to XML - update/alter the nodes of an XML Document


text:
Q: evaluate a function in the calling environment I have the function below.
test_fun <- function() {
  a <- 1
  b <- 2
}

Is there a way I run this function and a and b will be assigned in the parent environment (in this case globalenv)? I don't want to modify the function (no assign with envir or <<-), but call it in a way that what I want will be achieved.

A: Normally R functions return their outputs.  Functions such as test_fun
are discouraged but if you want to do it anyways use trace as shown below.  This will cause the code given in the exit argument to run at function exit.  No packages are used.
trace("test_fun", exit = quote(list2env(mget(ls()), globalenv())), print = FALSE)
test_fun()
a;b
## [1] 1
## [1] 2

Alternatives
Some alternatives for the exit= argument are the following.
(a) below is similar to above except that rather than leaving the objects loose in the global environment it first creates an environment env in the global environment and puts them there.
In (b) below, the objects are copied to environment(test_fun) which is the environment in which test_fun is defined.  (If test_fun is defined in the global environment then it gives the same result as the code at the top of the answer.)
In (c) below, the parent frame of test_fun is the environment of the caller of test_fun and can vary from one call to another if called from different places.  (If called from the global environment then it gives the same result as the code at the top of the answer.)
It would also be possible to add the current frame within test_fun to the search path using attach but there are a number of gotchas associated with that so it is not shown.
# (a) copy objects to environment env located in global environment
assign("env", new.env(), globalenv())
trace("test_fun", exit = quote(list2env(mget(ls()), env)), print = FALSE)

# (b) copy objects to environment in which test_fun is defined
trace("test_fun",
  exit = quote(list2env(mget(ls()), environment(test_fun)), print = FALSE)

# (c) copy object to parent.frame of test_fun; 5 needed as trace adds layers
trace("test_fun", exit = quote(list2env(mget(ls()), parent.frame(5))),
  print = FALSE)

A: A better pattern to use, from the point of encapsulation, might be to have your custom function return a 2D vector containing the a and b values:
test_fun <- function() {
    a <- 1
    b <- 2
    return(c(a, b))
}

result <- test_fun()
a <- result[1]
b <- result[2]

The preferred method for passing information/work done in a function is via the return value, rather than trying to manage the issue of different scopes.


text:
Q: Erlang can not receive message from where it begins There are two files here.
temp_converter() ->
receive
    {convertToCelsius, {From, TempF}} ->
        io:format("Temp-Server2 > Converter received message from ~w~n", [From]),
        ConvertedTempC = (TempF-32)*5/9,
        From ! finished,
        From ! {converted, ConvertedTempC},
        temp_converter();
    {From, {convertToCelsius, TempF}} ->
        io:format("Temp-Server > Converter received message from ~w~n", [From]),
        ConvertedTempC = (TempF-32)*5/9,
        From ! {converted, ConvertedTempC},
        temp_converter()
end.

The other one is:
sensor(Temp, Temp_Node, Dis_Node) ->
receive
    finished ->
        io:foramt("finished");
    % Receive the clock_tick from clock controller
    clock_tick ->
        io:format("Sensor_f received tick~n", []),
        {temp_converter, Temp_Node} ! {convertToCelsius, {self(), Temp}};
    % Receive the temperature which has been converted
    {converted, ConvertedTemp} ->
        io:format("Sensor_f received converted temperature~n", []),
        {display_module, Dis_Node} ! {inCelsius, ConvertedTemp};
    {'EXIT', From, Reason} ->
        io:foramt("Temperature Server down!~nGot ~p~n", [{'EXIT', From, Reason}])
end.

Basically, the sensor will send message to temp_converter, which is implemented in "clock_tick ->". When temp_converter received message, it will output something and send message back. Here is the problem.
It does output something, but sensor can not receive message from temp_converter. Is there anything wrong with my code? I also tried to send "finished" message back, but it still does not work!!
How can I send message back? How can I change "From ! finished" and "From ! {converted, ConvertedTempC}," to be correct?

A: In the conversion:
{convertToCelsius, {From, TempF}} ->
    io:format("Temp-Server2 > Converter received message from ~w~n", [From]),
    ConvertedTempC = (TempF-32)*5/9,
    From ! finished, %% Here you send to sensor the message 'finished'
    From ! {converted, ConvertedTempC}, %% the conversion will be received                                    %% after the first message (guaranteed by Erlang VM)
    temp_converter();

And in the sensor:
finished ->
    io:foramt("finished"); %% when you receive the first message, you print it
                           %% and leave the function. The next message will be lost
                           %% because you do not loop in the sensor function.

you only have to recall sensor(Temp, Temp_Node, Dis_Node) after the receive bloc and it should be fine.
Note that the message finished is useless in your case and that a simple call to a conversion function should do the job.


text:
Q: dnx . ef command returns System.InvalidOperationException I'm running Visual Studio 2015 on Windows 10 Tech Preview.
This is what I have for dnvm list:

Active Version           Runtime Architecture Location
  Alias
  ------ -------           ------- ------------ --------                     -----
         1.0.0-beta4       clr     x64          C:\Users\Jonas.dnx\runtimes
         1.0.0-beta4       clr     x86          C:\Users\Jonas.dnx\runtimes default
         1.0.0-beta4       coreclr x64          C:\Users\Jonas.dnx\runtimes           *    1.0.0-beta4       coreclr
  x86          C:\Users\Jonas.dnx\runtimes
         1.0.0-beta5-12021 clr     x86          C:\Users\Jonas.dnx\runtimes
         1.0.0-beta5-12087 coreclr x86          C:\Users\Jonas.dnx\runtimes

This is the error I'm getting with dnx . ef:

dnx : System.InvalidOperationException: Failed to resolve the following dependencies for target framework
  'DNXCore,Version=v5.0': At line:1 char:1
  + dnx . ef
  + ~~~~~~~~
      + CategoryInfo          : NotSpecified: (System.InvalidO...,Version=v5.0'::String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError
EntityFramework.Commands 7.0.0-beta4    EntityFramework.SqlServer
  7.0.0-beta4    Microsoft.AspNet.Authentication.Cookies 1.0.0
  -beta4    Microsoft.AspNet.Authentication.Facebook 1.0.0-beta4    Microsoft.AspNet.Authentication.Google 1.0.0-beta4
  Microsoft.AspNet.Authentication.MicrosoftAccount 1.0.0-beta4
  Microsoft.AspNet.Authentication.Twitter 1.0.0-beta4
  Microsoft.AspNet.Diagnostics 1.0.0-beta4
  Microsoft.AspNet.Diagnostics.Entity 7.0.0-beta4
  Microsoft.AspNet.Identity.EntityFramework 3.0.0-beta4
  Microsoft.AspNet.Mvc 6.0.0-beta4    Microsoft.AspNet.Mvc.TagHelpers
  6.0.0-beta4    Microsoft.AspNet.Server.IIS 1.0.0-beta4    Microsoft.AspNet.Server.WebListener 1.0.0-beta4
  Microsoft.AspNet.StaticFiles 1.0.0-beta4
  Microsoft.AspNet.Tooling.Razor 1.0.0-beta4    Microsoft.CSharp
  4.0.0-beta-22816    Microsoft.Framework.CodeGenerators.Mvc 1.0.0-beta4    Microsoft.Framework.ConfigurationModel.Json 1.0.0-beta4
  Microsoft.Framework.ConfigurationModel.UserSecrets 1.0.0-beta4
  Microsoft.Framework.Logging 1.0.0-beta4
  Microsoft.Framework.Logging.Console 1.0.0-beta4    Microsoft.Net.Http
  2.2.29    Microsoft.Owin.Security.Facebook 3.0.1    Microsoft.VisualStudio.Web.BrowserLink.Loader 14.0.0-beta4
  Microsoft.WindowsAzure.ConfigurationManager 3.1.0
  System.Collections 4.0.10-beta-22816    System.Linq 4.0.0-beta-22816
  System.Threading 4.0.10-beta-22816    WindowsAzure.Storage
  4.4.1-preview
Searched Locations:   C:\Users\Jonas\Dropbox\Visual Studio 2015
  Projects{name}\project.json   C:\Users\Jonas\Dropbox\Visual Studio
  2015 Projects\TestSite\src{name}\project.json
  C:\Users\Jonas\Dropbox\Visual Studio 2015
  Projects\TestSite\test{name}\project.json
Try running 'dnu restore'.
at Microsoft.Framework.Runtime.DefaultHost.GetEntryPoint(String
  applicationName)    at
  Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost
  host, String applicationName, String[] args)    at
  Microsoft.Framework.ApplicationHost.Program.Main(String[] args)

dnu restore returns these kinds of errors:

dnu : npm ERR! install Couldn't read dependencies At line:1 char:1
  + dnu restore
  + ~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (npm ERR! instal...ad dependencies:String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError   npm   ERR!  Windows_NT 6.3.9600
npm   ERR!   argv  "C:\Program Files (x86)\nodejs\\node.exe"
  "C:\Program Files (x86)\nodejs\node_modules\npm\bin\npm-cli.js"
  "install"
npm   ERR!   node  v0.12.4
npm   ERR!   npm   v2.10.1
npm   ERR!

npm debug log file has this:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files (x86)\\nodejs\\\\node.exe',
1 verbose cli   'C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install' ]
2 info using npm@2.10.1
3 info using node@v0.12.4
4 verbose readDependencies loading dependencies from C:\Users\Jonas\Dropbox\Visual Studio 2015 Projects\TestSite\package.json
5 error install Couldn't read dependencies
6 verbose stack Error: ENOENT, open 'C:\Users\Jonas\Dropbox\Visual Studio 2015 Projects\TestSite\package.json'
6 verbose stack     at Error (native)
7 verbose cwd C:\Users\Jonas\Dropbox\Visual Studio 2015 Projects\TestSite\artifacts\bin\TestSite\Debug\app
8 error Windows_NT 6.3.9600
9 error argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
10 error node v0.12.4
11 error npm  v2.10.1
12 error path C:\Users\Jonas\Dropbox\Visual Studio 2015 Projects\TestSite\package.json
13 error code ENOPACKAGEJSON
14 error errno -4058
15 error package.json ENOENT, open 'C:\Users\Jonas\Dropbox\Visual Studio 2015 Projects\TestSite\package.json'
15 error package.json This is most likely not a problem with npm itself.
15 error package.json npm can't find a package.json file in your current directory.
16 verbose exit [ -4058, true ]

I don't know where to start to fix the errors. I haven't found a suggestion that worked.
Thanks for your help.

UPDATE
I resolved it by installing bower and gulp. I don't know why I had to do it now as I never needed it in previous ef migrations on the same project.


text:
Q: Is there any way to pass state other than context or props? https://reactjs.org/docs/context.html states:

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

https://reactnavigation.org/docs/hello-react-navigation states:

Note: By default, React Navigation applies optimizations to screen components to prevent unnecessary renders. Using a render callback removes those optimizations. So if you use a render callback, you'll need to ensure that you use React.memo or React.PureComponent for your screen components to avoid performance issues.

and also states:

*

*Use React context and wrap the navigator with a context provider to pass data to the screens (recommended).

*Use a render callback for the screen instead of specifying a component prop:

This implies in React Navigation, for performance, you really want context which destroys the re-usability. Is there a 3rd way (e.g. recoiljs or any other things that may have come about)? I am hoping to possibly get the best of both somehow.

A: if i'm getting you right you want to pass props to another component without props drilling.
what i would suggest is to use the navigation hook navigate/push methods like this -
const navigation = useNavigation()
onPress={() => navigation.push('ScreenName',{'item': item})}
onPress={() => navigation.navigate('ScreenName',{'item': item})}

when item is the prop, and in the other screen you could accsess it using
route.params.item


text:
Q: How to pivot table back to original entry format import pandas as pd

import numpy as np

df=pd.DataFrame(np.array([['M',1, 1, 2, 3],
['F', 2, 4, 5, 6], ['M', 3, 7, 8, 9]]),columns=['SEX','AGE','A','B','C'])

dfm=pd.melt(df,id_vars=('SEX','AGE'),value_vars=list(df.columns[2:]),
         var_name='LOCATION',value_name='DEATHS')

Based on the code provided i can create a basic table and melt the tables from df to dfm using the 'AGE' and 'SEX' as id variables.
Is there a simple way of reverting this table back to its original format ?
Going from dfm > df assuming i do not have df.
many thanks

A: The pivot_table method should allow you to return to the original dataframe
# Change data types from object integer
dfm[['AGE', 'DEATHS']] = dfm[['AGE', 'DEATHS']].astype(int)

# Pivot dataframe to "undo melt"
reshaped = dfm.pivot_table(index=['SEX', 'AGE'],columns=['LOCATION'],
                           values='DEATHS')

# Reset index to flatten dataframe
reshaped.reset_index(inplace=True)

# Change column name attribute to blank
reshaped.columns.rename('',inplace=True)

   SEX  AGE A   B   C
0   F   2   4   5   6
1   M   1   1   2   3
2   M   3   7   8   9