text:
Q: Not able to start Tomcat using ant commands I have a tomcat folder. I am able to start tomcat using catalina.bat run command as well as startup.bat command from cmd prompt and able to access the URL: http://localhost:6080/
But I have the below setenv.bat
@echo off

rem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rem DO NOT MODIFY THE TEMPLATE FILE.  INSTEAD, COPY THIS FILE AS setenv.bat
rem AND MAKE THE NECESSARY CHANGES IN THAT FILE.
rem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

rem - - - - - - - - - - - - - - - - - - - - - - -
rem Set JAVA_HOME to a valid JDK installation dir
rem     e.g. set JAVA_HOME=C:\apps\java\1.6.0.14
rem - - - - - - - - - - - - - - - - - - - - - - -
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25

rem - - - - - - - - - - - -  - - - - - - - - - -
rem Set ANT_HOME to a valid ANT installation dir
rem     e.g. set ANT_HOME=C:\apps\ant\1.8.2
rem - - - - - - - - - - - -  - - - - - - - - - -
set ANT_HOME=C:\my_work\DOM\DSGI\ENV_SETUP\apache-ant-1.9.4

rem - - - - - - - - - - - - - - - - - - - - - - - - - - -
rem Set PATH to include bin directories from JDK and ANT
rem - - - - - - - - - - - - - - - - - - - - - - - - - - -
set PATH=%JAVA_HOME%\bin;%ANT_HOME%\bin;%LIBPATH%;%PATH%

rem - - - - - - - - - - - - - - - - - - - - - - - -
rem Set ANT_OPTS to increase the ANT runtime memory
rem e.g. set ANT_OPTS=-Xmx1444m -XX:MaxPermSize=256m
rem - - - - - - - - - - - - - - - - - - - - - - - -
set ANT_OPTS=-Xmx1444m -XX:MaxPermSize=256m

@echo on

When I am trying to start tomcat using the ant tomcat is not coming up and i am not able to access the URL.
first I executed setenv.bat
after that when i am doing ant start its gining the below result.
C:\app\scope\olm\scope-studio\mip-2015>ant start
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre7\lib\tools.jar
Buildfile: C:\app\scope\olm\scope-studio\mip-2015\build.xml

-init:
     [echo] Current OS Family: windows
     [echo] ANT_HOME is set to = C:\my_work\DOM\DSGI\ENV_SETUP\apache-ant-1.9.4
     [echo] JAVA_HOME is set to = C:\Program Files\Java\jdk1.7.0_25

start:
     [echo] MIP tomcat server instance started

BUILD SUCCESSFUL
Total time: 25 seconds


text:
Q: How do I adjust the spacing around the sides of list items in jquery mobile I have a list of things like this:

<item 1/li>

item 2

However, the sides of this keep stretching to the very end of the page. How could I add some kind of padding around the edges like in the api example found here:  http://jquerymobile.com/demos/1.2.0/docs/lists/lists-nested.html
I know I can add some css that would ajust the margin, However I don't want this to be added when viewing the page on a cell phone
Thanks

A: Well you can go with a standard solution:

<item 1/li>

item 2

Or you can go all commando like this:
.ui-listview {
    margin: 20px !important;
}

Working example: http://jsfiddle.net/Gajotres/2PhBQ/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing array lists from threads I am making a multiplayer adventure game for my networking class. I have a client and a server, the server is multithreaded, and kicks off a new thread whenever it gets a new client connected. I have an array list that keeps track of the players to make sure that a new player isn't added. For some reason, when a new client connects, it takes the place of the old one as well as filling a new spot. Here is my code for this part
public class ClientHandler implements Runnable{
private AsynchronousSocketChannel clientChannel;
private static String command[];
private static String name;
private static GameCharacter character;
public ClientHandler(AsynchronousSocketChannel clientChannel)
{
    this.clientChannel = clientChannel;
}

public void run(){
    try{
        System.out.println("Client Handler started for " + this.clientChannel);
        System.out.println("Messages from Client: ");
        while ((clientChannel != null) && clientChannel.isOpen()) {
            ByteBuffer buffer = ByteBuffer.allocate(32);
            Future result = clientChannel.read(buffer);
            //Wait until buffer is ready
            result.get();
            buffer.flip();
            String message = new String(buffer.array()).trim();
            if(message == null || message.equals(""))
            {
                break;
            }
            System.out.println(message);
            clientChannel.write(buffer);
            try {
                //Add the character to the routing table and the character table
                if (message.contains("connect")) {
                    System.out.println("I'm here too?");
                    command = message.split(" ");
                    name = command[1];
                    AdventureServer.userInfo.put(name, this);
                    //Check to see if this game character exists
                    GameCharacter test;
                    boolean exists = false;
                    for(int i=0; i < AdventureServer.characters.size(); i++)
                    {
                        test = AdventureServer.characters.get(i);
                        System.out.println(test.getName());
                        System.out.println(this.name);
                        if(this.name.equals(test.getName()))
                        {
                            System.out.println("already Here");
                            exists = true;
                        }
                    }
                    if (exists == true)
                    {
                        //This person has connected to the server before
                    }
                    else {
                        //Create a game character
                        System.out.println("didn't exist before");
                        character = new GameCharacter(this.name, World.getRow(), World.getCol());
                        AdventureServer.characters.add(AdventureServer.userInfo.size() - 1, character);
                        System.out.println(AdventureServer.characters.get(0).getName() + " " +AdventureServer.characters.get(1).getName());
                    }
                }

I understand that the print lines at the bottom will throw an error for the first client that connects, but that is not part of the issue.
And here is the declaration of the server
public class AdventureServer {
public static Map<String, ClientHandler> userInfo = new HashMap<>();
public static World world;
public static List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>());
public static void main(String args[]) {
    //Create the games map that all of the users will exist on
    world = new World(args[0]);

    System.out.println("Asynchronous Chat Server Started");
    try {
        AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();
        InetSocketAddress hostAddress = new InetSocketAddress("192.168.1.7", 5000);
        serverChannel.bind(hostAddress);
        while (true)
        {
            System.out.println("Waiting for client to connect");
            Future acceptResult = serverChannel.accept();
            AsynchronousSocketChannel clientChannel = (AsynchronousSocketChannel) acceptResult.get();
            new Thread (new ClientHandler(clientChannel)).start();
        }
    } catch (Exception e) {
        System.out.println("error interrupted");
        e.printStackTrace();
        System.exit(0);
    }
}
}

Here is my constructor for game characters
public class GameCharacter {
public static int xpos;
public static int ypos;
private static String name;
private static int rowSize;
private static int columnSize;
static List<String> inventory = new ArrayList<>();

//Constructor
GameCharacter(String n, int rSize, int cSize)
{
    xpos = 0;
    ypos = 0;
    name = n;
    rowSize = rSize;
    columnSize = cSize;
}

GameCharacter()
{
    xpos = 0;
    ypos = 0;
    name = "billybob";
    rowSize = 10;
    columnSize = 10;
}

A: As a matter of readability, testability, and style, I would also recommend you not directly access data structures belonging to another class. Instead of
   Adventureserver.characters.add(blah blah)

I would recommend making characters a private field of Adventureserver, and then creating a method to add or remove characters from it. In fact, I would be inclined not to make characters static -- there is no real advantage, and you might at some point want more than one Adventureserver running.
Sort of like so:
public class AdventureServer {
<...>
private List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>);

<...>
public void addCharacter(GameCharacter char) {
   <... error checking ...>
   characters.add(char);
}
public void removeCharacter(GameCharacter char) {
   <... implementation ... >
}
public boolean isCharacterHere(GameCharacter char) {
}
public List<GameCharacter> getCharacters() {
  <... you could either return characters here, or a copy of it,
   depending upon how paranoid you want to be >

A: You can try:
public static volatile List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>());

Update:
The problem is that you are using a non synchronized HashMap userInfo.
Change that line from:
AdventureServer.characters.add(AdventureServer.userInfo.size() - 1, character);

To:
AdventureServer.characters.add(character);

Or make your HashMap Synchronized:
public static Map<String, ClientHandler> userInfo = Collections.synchronizedMap(new HashMap<>());

All those static declarations are making problems, you should remove them. In general you should avoid using static.
ClientHandler:
private static String command[];
private static String name;
private static GameCharacter character;

GameCharacter:
public static int xpos;
public static int ypos;
private static String name;
private static int rowSize;
private static int columnSize;
static List<String> inventory = new ArrayList<>();

Just a side note, this way your Class is more like Java code should look like:
import java.util.ArrayList;
import java.util.List;

public class GameCharacter {
private int xpos;
private int ypos;
private String name;
private int rowSize;
private int columnSize;

private List<String> inventory = new ArrayList<>();

// Constructor
GameCharacter(String n, int rSize, int cSize) {
    this.xpos = 0;
    this.ypos = 0;
    this.name = n;
    this.rowSize = rSize;
    this.columnSize = cSize;
}

GameCharacter() {
    this.xpos = 0;
    this.ypos = 0;
    this.name = "billybob";
    this.rowSize = 10;
    this.columnSize = 10;
}

public int getXpos() {
    return xpos;
}

public void setXpos(int xpos) {
    this.xpos = xpos;
}

public int getYpos() {
    return ypos;
}

public void setYpos(int ypos) {
    this.ypos = ypos;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getRowSize() {
    return rowSize;
}

public void setRowSize(int rowSize) {
    this.rowSize = rowSize;
}

public int getColumnSize() {
    return columnSize;
}

public void setColumnSize(int columnSize) {
    this.columnSize = columnSize;
}

public List<String> getInventory() {
    return inventory;
}

public void setInventory(List<String> inventory) {
    this.inventory = inventory;
}

}


text:
Q: How to get a previous value of a serie (SMA) regardless of the timeframe selected? I'm trying to do the following :

*

*generate 4 SMA (SMA7 / 20 / 50 / 100) on a MTF (multi-timeframe) : for example for the hourly and daily timeframes

[S1, S7, S13, S19] = request.security(syminfo.tickerid, "60", [ma7, ma20, ma50, ma100], lookahead=barmerge.lookahead_on)
[S2, S8, S14, S20] = request.security(syminfo.tickerid, "D", [ma7, ma20, ma50, ma100], lookahead=barmerge.lookahead_on)
--> I checked that the values are ok by setting them on a table : it seems to work correctly, and even if I change the timeframe on Tradingview the values are stills (so it should be regarding I fixes the timeframe on each serie).

*

*comparing the current value of the SMA with one in the past (5 periods in the example below), so I can determine if its increasing or decreasing, for example below by setting in a variable the result :

sma7direction = if S1[0] > S1[5]
"Up"
else
"Down"
It works but only when I'm on the same timeframe as the serie, so in my example if I'm on the hourly timeframe. Once I set TradingView on another timeframe, I get an incorrect value on S1[5] so I think the behavior is that the 5 periods in the past are not on the hourly timeframe but in the one I've selected on Tdw ...
How can I get 5 periods in the past with a fix timeframe ?
Thanks in advance for any help you can provide :)

A: *

*As a general rule, do NOT use lookahead with request.security() as you are then introducing future leak in your scripts. See here for more information.

*The reason it's not working when the chart's TF is not the same as that of the request.security() call is because you are referring to previous values of the HTF when reported at the chart's TF, so they will be the same value on all chart bars until the HTF changes.

*If you want to refer to past values in the HTF's context, you need to evaluate them inside your request.security() call, so you could use:

[S1, S7, S13, S19, S1Rising] = request.security(syminfo.tickerid, "60", [ma7, ma20, ma50, ma100, ma7 > ma7[5])


text:
Q: In JavaScript and HTML, how can I get the access to the  that the current button locates? In HTML, I have

      <button onclick="action()">button</button>

Without giving an ID or class to the   div element, what can I do in JavaScript to get an access to it and use it?

A: Pass this into action:
<button onclick="action(this)">button</button>

and then in action
function action(btn) {
    var div = btn.parentNode;
    // ...
}

or if you want a bit more flexibility, use the (relatively-new) closest method:
function action(btn) {
    var div = btn.closest("div");
    // ...
}

Side note: Rather than onxyz-attribute-style event handlers, consider using modern event handling (addEventListener, attachEvent on obsolete browsers). If you have to support obsolete browsers, my answer here provides a function you can use to deal with the lack of addEventListener.

A: using this in the onclick=action() and then the parent is .parentNode
then your method would look like :

  <button onclick="action(this);">button</button>

function action(el) {
  console.log(el.parentNode);
}

but I rather prefer .addEventListenerand for your next question then :

var $el = document.getElementById("a");
$el.addEventListener("click", function(e) {
  // Create a <button> element
  var btn = document.createElement("BUTTON");
  // Create a text node
  var t = document.createTextNode("CLICK ME");
  // Append the text to <button>
  btn.appendChild(t);
  // Append <button> to the parentNode
  this.parentNode.appendChild(btn);
});

  <button id="a">Button</button>

Also in case you wonder for a shorter version and probably introducing to the jQuery :

;$(function(){
  $("#a").on("click", function(e) {
    $(this).parent().append('<button>Click Me</button>');
  });
});

  <button id="a">Button</button>

Another but not straight way to get the parent instead of .parentNode is .closest() method:
element.closest("div"); // also supported in jQuery

Returns the first ancestor of element, that is a
 element:

A: Grab the event then get the currentTarget then find the parentNode. Very simple way to do it.  This will work no matter which element is clicked. Please see code snippet demonstration.

function getParentNode(event) {
  console.log(event.currentTarget.parentNode);
}

<button onclick="getParentNode(event)">Click</button>

<button onclick="getParentNode(event)">Click</button>

A: If it is possible, pass this (button) to action. Then you can access parent by element.parentNode. Example: https://jsbin.com/fidufa/edit


text:
Q: Jquery Ajax issue I am working on a tip popup windows for my project. When the user clicks the 'turn on tips' button, the tips windows will show next to some elements.
My problem is that I have elements created from ajax that need to have tips window shown next to them as well and if the user clicks the button BEFORE ajax call, those element won't have tips windows shown because they didn't exist. Are there any suggestions to this problem? Thank a lot.

A: You could use on() to act as a delegate for dynamic elements to bind events.
Below, I am registering click events to any event that now or later exists on the document with a class called tips.
$(document).on('click','.tips', function(){
   // show tips;
});

A: I solve issues like this by having a function I call dommods(). When called, it applies any effects I want to the document, such as tooltips. I simply call it after every change to the DOM, and that solves the problem.


text:
Q: Attempt to invoke virtual method xx on a null object reference when I try to reload the activity I've an activity whuich load some data from mySql db to populate a Recyclerview.
PollActivity.java (relevant code)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_poll);

    rv = findViewById(R.id.rv);

    // *** Rv Init ***
    LinearLayoutManager llm = new LinearLayoutManager(this);
    rv.setLayoutManager(llm);
    rv.setHasFixedSize(false);
    polls = new ArrayList<>();

    // SqLite data management
    db = new SQLiteHandler(getApplicationContext());
    HashMap<String, String> user = db.getUserDetails();
    final String userid = user.get("uid");
    // Local data
    String localBefore = Locale.getDefault().getLanguage().toUpperCase();
    final String local;
    switch (localBefore){

        case "IT":

            local = "IT";
            break;

        case "FR":

            local = "FR";
            break;

        case "DE":

            local = "DE";
            break;

        case "ES":

            local = "ES";
            break;

        default:

            local = "EN";
            break;

    }

    // ************
    // *** MAIN ***
    // ************

    // Tag used to cancel the request
    String tag_string_req = "req_login";

    MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
            .title(R.string.strDialogProgressLoading_title)
            .content(R.string.strDialogProgressReg_desc)
            .progress(true, 0);
    final MaterialDialog myDialog = builder.build();
    myDialog.show();

    StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_LOADING, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {

                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) {

                    for(int i=0; i<jObj.length()-2; i++){

                        int j = i + 1;
                        JSONObject pollObject = jObj.getJSONObject("poll" + i);
                        JSONObject pollObjectNext = jObj.getJSONObject("poll" + j);
                        i++;

                        //Id to String Translate
                        int idInterests = getResources().getIdentifier("strInterestsItem" + pollObject.getString("id_interests"), "string", getPackageName());
                        String strInterests = getString(idInterests);

                        String strPoint;
                        if(pollObject.getString("sponsor").equals("UUABA")){

                            strPoint = "+200";

                        }else{

                            strPoint = "+150";

                        }

                        //String concatenation
                        String idPoll = "#" + pollObject.getString("id_poll");
                        String strQuestion = "#" + pollObject.getString("poll_question");
                        String IdUser = userid;

                        polls.add(new Poll(idPoll
                                , pollObject.getString("sponsor")
                                , pollObject.getString("poll_user_state")
                                , IdUser
                                , strInterests
                                , strQuestion
                                , pollObject.getString("poll_answer")
                                , pollObject.getString("id_poll_answer")
                                , pollObjectNext.getString("poll_answer")
                                , pollObjectNext.getString("id_poll_answer")
                                , strPoint));

                    }

                    initializeAdapter();
                    myDialog.dismiss();

                } else {

                    myDialog.dismiss();
                    // Error in loading. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
                    String strErrorRes = getString(idErrorRes);

                    //POPUP ERRORE
                    new MaterialDialog.Builder(PollActivity.this)
                            .title(getResources().getString(R.string.strDialogAttention_title))
                            .titleColor(getResources().getColor(R.color.colorAccentDark))
                            .content(strErrorRes)
                            .positiveText(R.string.strDialogBtnPositive)
                            .contentGravity(GravityEnum.CENTER)
                            .positiveColor(getResources().getColor(R.color.colorAccent))
                            .icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
                            .cancelable(false)
                            .autoDismiss(false)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            myDialog.dismiss();

            //POPUP ERRORE
            new MaterialDialog.Builder(PollActivity.this)
                    .title(getResources().getString(R.string.strDialogAttention_title))
                    .titleColor(getResources().getColor(R.color.colorAccentDark))
                    .content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
                    .positiveText(R.string.strDialogBtnPositive)
                    .contentGravity(GravityEnum.CENTER)
                    .positiveColor(getResources().getColor(R.color.colorAccent))
                    .icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
                    .cancelable(false)
                    .autoDismiss(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .show();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to loading url
            Map<String, String> params = new HashMap<String, String>();
            params.put("userid", userid);
            params.put("local", local);

            //Log.d("NINJA", "UserID: " + userid);
            //Log.d("NINJA", "Local: " + local);
            return params;

        }

    };

    // Adding request to request queue
    AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);

    // ************
    // ************
    // ************

private void initializeAdapter(){

    RVAdapter adapter = new RVAdapter(polls);
    rv.setAdapter(adapter);

}

public void reloadActivity(){

    startActivity(getIntent());
    finish();

}

}

RVAdapter.java(my Recycler View Adapter)
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PollViewHolder> {

public static class PollViewHolder extends RecyclerView.ViewHolder {

    CardView cv;
    TextView txtIdPoll;
    ImageView imgSponsor;
    ImageView imgNew;
    TextView txtIdInterests;
    TextView txtQuestion;
    RadioGroup radioGroupAnswers;
    RadioButton radioAnswer1;
    RadioButton radioAnswer2;
    Button btnPoint;

    PollViewHolder(View itemView) {

        super(itemView);

        cv = itemView.findViewById(R.id.cv);
        txtIdPoll = itemView.findViewById(R.id.txtIdPoll);
        imgSponsor = itemView.findViewById(R.id.imgSponsor);
        imgNew = itemView.findViewById(R.id.imgNew);
        txtIdInterests = itemView.findViewById(R.id.txtIdInterests);
        txtQuestion = itemView.findViewById(R.id.txtQuestion);
        radioGroupAnswers = itemView.findViewById(R.id.radioGroupAnswers);
        radioAnswer1 = itemView.findViewById(R.id.radioAnswer1);
        radioAnswer2 = itemView.findViewById(R.id.radioAnswer2);
        btnPoint = itemView.findViewById(R.id.btnPoint);

    }
}

List<Poll> polls;
//Context context;

public RVAdapter(List<Poll> polls){

    this.polls = polls;
    //this.context = context;

}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {

    super.onAttachedToRecyclerView(recyclerView);

}

@Override
public PollViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.poll_item, viewGroup, false);
    PollViewHolder pvh = new PollViewHolder(v);
    return pvh;

}

@Override
public void onBindViewHolder(final PollViewHolder pollViewHolder, final int i) {

    final int rb1id = 1000;
    final int rb2id = 2000;

    //Setting RadioButton ID
    pollViewHolder.radioAnswer1.setId(rb1id);
    pollViewHolder.radioAnswer2.setId(rb2id);

    pollViewHolder.txtIdPoll.setText(polls.get(i).txtIdPoll);

    if(polls.get(i).txtSponsor.equals("UUABA")){

        pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_logo_red_bg);

    }else{

        pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_sponsor_green_bg);

    }

    if(polls.get(i).txtNew.equals("0")){

        pollViewHolder.imgNew.setImageResource(R.drawable.ic_new);

    }else{

        pollViewHolder.btnPoint.setEnabled(false);
        pollViewHolder.btnPoint.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);

    }

    pollViewHolder.txtIdInterests.setText(polls.get(i).txtIdInterests);
    pollViewHolder.txtQuestion.setText(polls.get(i).txtQuestion);
    pollViewHolder.radioAnswer1.setText(polls.get(i).txtAnswer1);
    pollViewHolder.radioAnswer2.setText(polls.get(i).txtAnswer2);
    pollViewHolder.btnPoint.setText(polls.get(i).txtPoint);

    pollViewHolder.btnPoint.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId() == -1){

                Snackbar snackbar = Snackbar.make(v, R.string.strSnackPoll, Snackbar.LENGTH_LONG);
                View snackbarView = snackbar.getView();
                TextView textView =snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.YELLOW);
                snackbar.show();

            }else{

                QueryUtils queryUtils = new QueryUtils();
                String IdPoll = String.valueOf((polls.get(i).txtIdPoll)).replace("#", "");

                switch (pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId()){

                    case 1000:

                        queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer1)));
                        break;

                    case 2000:

                        queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer2)));
                        break;

                }

            }

        }
    });

}

@Override
public int getItemCount() {

    return polls.size();

}

}

At this point, I would like to update a db field at button click and reload PollActivity.java to force the RecyclerView update (I'd like that the NEW image disappear from the updated CardView). I guess to do this calling a method of my QueryUtils.java (one of the method it will contain), avoiding to write too mutch code inside adapter.
QueryUtils.java
@SuppressLint("Registered")
public class QueryUtils extends Application {

private String tag_string_req = "req_poll_answer_upg";

public void upgPollAnswer(final String UserId, final String PollId, final String AnswerId){

    Log.d("NINJA", "Utente: " + UserId);
    Log.d("NINJA", "Poll: " + PollId);
    Log.d("NINJA", "Risposta: " + AnswerId);

    StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_ANSWER_UPG, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {

                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                String message = jObj.getString("message");

                if (!error) {

                    Log.d("NINJA", "Messaggio: " + message);
                    PollActivity pollActivity = new PollActivity();
                    pollActivity.reloadActivity();

                } else {

                    //myDialog.dismiss();

                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
                    String strErrorRes = getString(idErrorRes);

                    Log.d("NINJA", "ErrorePhP: " + strErrorRes);
                    //POPUP ERRORE
                    /*new MaterialDialog.Builder(QueryUtils.this)
                            .title(getResources().getString(R.string.strDialogAttention_title))
                            .titleColor(getResources().getColor(R.color.colorAccentDark))
                            .content(strErrorRes)
                            .positiveText(R.string.strDialogBtnPositive)
                            .contentGravity(GravityEnum.CENTER)
                            .positiveColor(getResources().getColor(R.color.colorAccent))
                            .icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
                            .cancelable(false)
                            .autoDismiss(false)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();*/

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            Log.d("NINJA", "ErroreVolley: " + error);
            //myDialog.dismiss();

            //POPUP ERRORE
            /*new MaterialDialog.Builder(QueryUtils.this)
                    .title(getResources().getString(R.string.strDialogAttention_title))
                    .titleColor(getResources().getColor(R.color.colorAccentDark))
                    .content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
                    .positiveText(R.string.strDialogBtnPositive)
                    .contentGravity(GravityEnum.CENTER)
                    .positiveColor(getResources().getColor(R.color.colorAccent))
                    .icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
                    .cancelable(false)
                    .autoDismiss(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .show();*/

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to loading url
            Map<String, String> params = new HashMap<String, String>();
            params.put("userid", UserId);
            params.put("id_poll", PollId);
            params.put("id_answer", AnswerId);

            return params;

        }

    };

    // Adding request to request queue
    AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

}

At the end of the update procedure, I call the reloadActivity method in PollActivity, to reload itself. THIS call generate the error below:
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
    at android.app.Activity.startActivityForResult(Activity.java:4226)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)
    at android.app.Activity.startActivityForResult(Activity.java:4183)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:751)
    at android.app.Activity.startActivity(Activity.java:4522)
    at android.app.Activity.startActivity(Activity.java:4490)
    at com.uuaba.uuaba.core.PollActivity.reloadActivity(PollActivity.java:345)
    at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:48)
    at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:33)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

I'm new in Android programming and I tried different solution found in this great forum, but none of them worked for me.
Please help me

A: Problem is that you are trying to create a new instance of activity without the use of intent :
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();

You should replace this code with the following lines:
public void onClickChangeActivity() {
    Intent intent = new Intent(this, PollActivity.class);
    startActivity(intent);
}

But your solution is far away from the ideal solutions available in the market. Restarting the activity whenever there is a change in data because you have to update data can never be a good way to go.
Try considering one of these ways to prevent activity restart

*

*Create a data stream(list of data) and keep on reading that on
activity level.

*Create a local broadcast receiver
Do let me know if you need help in above ways.
As a quick fix for the problem you can use this hackish way

*

*Create a callback
interface Result {
void success(ResponseModel model);
void failure(Throwable throw);
}

*In QueryUtils

List resultCallbacks = new ArrayList(); public void
  addCallback(Result result) { resultCallbacks.add(result); }

create List resultCallbacks and a method addCallback to add the callbacks

*In PollsActivity write this

((QueryApplication)getApplicationContext().getApplication()).addCallbacks(this);

and implement the callback.
On receiving any data update your list and do

RVUpdater.notifyDataSetChanged();

Hope this will help.


text:
Q: Can not download el Capitan I have an older Mac computer.  Apple tells me it will run OS thru El Capitan.  It is currently running snow leopard 10.6.8.
When I open "http://iTunes.apple.com/app/os-x-el-capitan/id1147835433?mt=12" I go to the Apple App Store and it says this is the El Capitan download.  There is a blue button on the left side of screen under the large X that says "Get".  If I click on this blue button, the button changes shade of blue as long as I hold the mouse button down, but nothing happens.  If I click on the down arrow on the right side of the blue button, I get two options, "copy link" and "tell a friend".

How do I download El Capitan?  I called Apple tech support (tier 2) and spend several hours downloading to 10.6.8, but Apple can not tell me why I can not download El Capitan from the App Store.  Any help appreciated!

A: If neither of the "direct" App Store links (1. El Capitan 2. El Capitan) as described in other answers like this one work, you can try to trick App Store - as elaborated here: Install OS X El Capitan on Mac Direct Download.
Here a local web server with all necessary files mimics the remote but stubborn Apple server.

*

*Open a browser and download the following files:

*

*OS X El Capitan .pfpkg file (direct link)

*OS X El Capitan .pkg file (direct link)

*Open Terminal.app and enter
sudo nano /etc/hosts

*add the following line at the end of the file: 127.0.0.1  osxapps.itunes.apple.com

*Hit ctrlO to write the file to disk and ctrlX to exit nano

*Enter sudo killall -HUP mDNSResponder to flush the DNS cache.

*Enter cd Desktop to change your working directory to your desktop

*Create a folder mkdir osxapps_local and cd to it: cd osxapps_local

*Create to paths with:
sudo mkdir -p ./apple-assets-us-std-000001/Purple60/v4/45/df/86/45df865d-d24d-01d6-2b2c-c003317293ac/
sudo mkdir -p ./apple-assets-us-std-000001/Purple20/v4/dc/94/05/dc940501-f06f-2a91-555e-3dc272653af5/

*move the downloaded files to the respective folders:
sudo mv ~/Downloads/signed.dcr.6112397842917719871.pfpkg ~/Desktop/osxapps_local/apple-assets-us-std-000001/Purple60/v4/45/df/86/45df865d-d24d-01d6-2b2c-c003317293a
sudo mv ~/Downloads/izt4803713449411067066.pkg  ~/Desktop/osxapps_local/apple-assets-us-std-000001/Purple20/v4/dc/94/05/dc940501-f06f-2a91-555e-3dc272653af5

*Start a small web server:
sudo python -m SimpleHTTPServer 80

*Now you can check if your small web server works by entering
http://osxapps.itunes.apple.com/apple-assets-us-std-000001/Purple20/v4/dc/94/05/dc940501-f06f-2a91-555e-3dc272653af5/izt4803713449411067066.pkg

in the address field of your browser. The file should be "downloaded" with a high download speed. Delete the downloaded file afterwards.

*Launch App Store.app, go to the El Capitan page or your Purchased tab and download OS X El Capitan from there.

*The OS X El Capitan Installer.app should be "downloaded", compiled in /Applications/ and launched. Quit the OS X Installer for now. Quit App Store.app.

*Quit the http server by entering ctrlC in Terminal.app

*Revert the changes of your hosts file:
sudo nano /etc/hosts

and remove the line 127.0.0.1  osxapps.itunes.apple.com.

*Hit ctrlO to write the file to disk and ctrlX to exit nano

*Quit Terminal.app

*Open /Application/Install OS X El Capitan.app and install El Capitan

A: So I had this exact problem as well, and it seemed to work just fine after installing all available software updates from the  menu.


text:
Q: rcdk R package fails to compute fingerprints from SMILES codes I am using smile codes for the FDA approved drugs available in chEMBL 22 database. I am using the package rcdk and I am using this code:
library(rcdk)

dat1<-read.csv("chembl_22_drug_export.txt",sep="\t",header=T)
smi <-lapply(as.character(dat1$CANONICAL_SMILES),parse.smiles)
cmp.fp<-vector("list",nrow(dat1))

## generate fingerprints
for (i in 1:nrow(dat1)){
  cmp.fp[i]<-lapply(smi[[i]][1],get.fingerprint,type="maccs")

}

##Convert fingerprints to matrix form
fpmac<-fp.to.matrix(cmp.fp)
cmp.finger<-as.data.frame(fpmac)

But when I do
smi <- lapply(as.character(chembl_22_drug_export$CANONICAL_SMILES), parse.smiles)

I get the following error
Error in .jnew("org/openscience/cdk/smiles/SmilesParser", dcob) :
  Java Exception <no description because toString() failed>.jnew("org/openscience/cdk/smiles/SmilesParser", dcob)<S4 object of class "jobjRef">

Kindly guide me how do I resolve this error?

A: The error is spewed when rcdk package is not installed. Error occurs because of fault loading due to rJava package requirement. rcdk package required jdk of 7 or more. echo JAVA_HOME and update the locale along with language as well. The environment variable should be updated. Close R and restart the R console after you update the java environment. Remember: rcdk package requires supporting library as fingerprints and rJava as well.


text:
Q: JQuery for fixed position of navigation bar Hello I am new to JavaScript please can anyone tell me the JQuery for keeping the navigation bar fixed on top while I scroll down.
I am using the following code but i think some contents are missing
Code Snippet :
var fixmeTop = $('.fixme').offset().top;
$(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    if (currentScroll >= fixmeTop) {
        $('.fixme').css({ position: 'fixed', top: '0', left: '0' });
    }
    else {
        $('.fixme').css({ position: 'static' });
    }
});

A: $( document ).ready(function() {
   var fixmeTop = $('.fixme').offset().top;
    $(window).scroll(function () {
        var currentScroll = $(window).scrollTop();
        if (currentScroll > fixmeTop) {
            $('.fixme').css({position: 'fixed', top: '0', left: '0'});
        } else {
            $('.fixme').css({position: 'static'});
        }
    });

});

A: If you want it fixed all the time, use something like:
.class_name {
    position: fixed;
}

If you want it fixed only when you scroll, but relative when you are at the top of the page, then use something like:
$('body').scroll(function(){

 var $class_name = $('.class_name');

 if($(this).scrollTop() >= $class_name.height()) {
  $class_name.addClass('scrolled');
 }
});

You can then use css to change the position based on the class on the element.
.class_name.scrolled {
    position: fixed;
}

If you couple this will transition css, you will be able to animate it smoothly.


text:
Q: Unexpected results implementing stacks with linked lists I am writting this program, and I want to understand why I am getting the wrong printing (which should de 1,2,3,4,5) gives some address instead. My stackIsEmpty() does not even act as it is meant to that is to stop printing values when the stack is empty. Here is my code:
#include <stdlib.h>
#include <stdio.h>

//Stacks using Structures and linked list and pointerws.

typedef struct Stack{
    //Type of the elements of the stack. Here integers
    int elem;
    //To of the stack
    struct Stack* previous;
} Stack;

void initialize(Stack *st);
void push(Stack *st, int element);
int pop(Stack *st);
int stackIsEmpty(Stack *st);

int main(){
    int i;
    Stack st;
    Stack *pt_st = &st;
    initialize(pt_st);

    //Test phase...
    for(i=0; i<5; i++)
        push(pt_st, i+1);

    for(i=0; i<5; i++)
        printf("here is one element: %d\n", pop(pt_st));
    //End of test with error!
    return 0;
}

void initialize(Stack *st){
    st = NULL;
}

void push(Stack *st, int element){
    Stack *sta = (Stack*)malloc(sizeof(Stack));
    if (sta != NULL)
    {
        sta->previous = st;
        sta->elem = element;
        st = sta;
        free(sta);
    }
    else
        exit(0);
}

int pop(Stack *st){
    if(!stackIsEmpty(st))
    {
        printf("stack is empty cannot pop\n");
        return 0;
    }
    else
    {
        int number = st->elem;
        Stack* copy = st->previous;
        free(st);
        st = copy;
        return number;
    }
}

int stackIsEmpty(Stack *st){
    if(st == NULL)
        return 0;
    else
        return 1;
}

A: The Stack pointer pt_st You've created is passed by value to the functions, so the functions only modifying a local copy of it.
You can create a pointer to pointer, or make pt_st a global variable.
Your push function also has problems.
I've modified your code, made pt_st global, so it works now:
#include <stdlib.h>
#include <stdio.h>

//Stacks using Structures and linked list and pointerws.

typedef struct Stack{
    //Type of the elements of the stack. Here integers
    int elem;
    //To of the stack
    struct Stack* previous;
} Stack;

void initialize();
void push(int element);
int pop();
int stackIsEmpty();

Stack *pt_st; // made pt_st global, so functions can modify it

int main(){
    int i;
    initialize();

    //Test phase...
    for(i=0; i<5; i++)
        push(i+1);

    for(i=0; i<5; i++)
        printf("here is one element: %d\n", pop(pt_st));
    //End of test with error!
    return 0;
}

void initialize(){
    pt_st = NULL; // set it to NULL
}

void push(int element){
    Stack *sta = malloc(sizeof(Stack)); // don't need to cast malloc
    sta->elem = element;

    sta->previous = pt_st; // set sta's previous

    pt_st = sta; // point to the pushed node
}

int pop(){
    if(stackIsEmpty())
    {
        printf("pt_stack is empty cannot pop\n");
        return 0;
    }
    else
    {
        int number = pt_st->elem;
        Stack *temp = pt_st; // create a temp copy of the first node's address
        pt_st = pt_st->previous;
        free(temp);
        return number;
    }
}

int stackIsEmpty(){
    if(pt_st == NULL)
        return 1; // if pt_st is NULL, then the stack is empty
    else
        return 0;
}

A: I think you need to read something about passing values by copy: What's the difference between passing by reference vs. passing by value?
initialize makes nothing, you pass an address (by value) so anything will be reported in you main. This is almost the same for every function. You also free immediately after having allocated a structure.
You must pass the pointer to stack by address, as the top of the stack is modified by your functions :
#include <stdlib.h>
#include <stdio.h>

//Stacks using Structures and linked list and pointerws.

typedef struct Stack{
    //Type of the elements of the stack. Here integers
    int elem;
    //To of the stack
    struct Stack* previous;
} Stack;

void initialize(Stack **st);
void push(Stack **st, int element);
int pop(Stack **st);
int stackIsEmpty(Stack *st);

int main(){
    int i;
    Stack *pt_st;
    initialize(pt_st);

    //Test phase...
    for(i=0; i<5; i++)
        push(&pt_st, i+1);

    for(i=0; i<5; i++)
        printf("here is one element: %d\n", pop(&pt_st));
    //End of test with error!
    return 0;
}

void initialize(Stack **st){
    *st = NULL;
}

void push(Stack **st, int element){
    Stack *sta = (Stack*)malloc(sizeof(Stack));
    if (sta != NULL)
    {
        sta->previous = *st;
        sta->elem = element;
        *st = sta; // new top of stack is sta
    }
    else
        exit(0);
}

int pop(Stack **st){
    if(!stackIsEmpty(*st))
    {
        printf("stack is empty cannot pop\n");
        return 0;
    }
    else
    {
        int number = (*st)->elem;
        Stack* copy = (*st)->previous;
        free(*st);
        *st = copy;
        return number;
    }
}

int stackIsEmpty(Stack *st){
    if(st == NULL)
        return 0;
    else
        return 1;
}

Also try to avoid to exit prematurely in your functions, it is better to return an error code and let the caller take the decision, something like:
//pseudo code
int push(...) {
   if alloc fails return -1
   else { do the trick; return 0;
}

...
if (push(...)==-1) { print "something's wrong"; exit 0; }

It should be slightly different with pop as you need both to return a value on success and an error code on failure:
int pop(Stack **st,int *pop) {
    if (staksIsEmpty(st)) return -1;
    *pop = *(st.elem);
    ...
    return 0;
}

...
int value;
if (pop(&pt_st,&value)==-1) //error


text:
Q: React Native:- Swipe gesture is not working on drawernavigator of react-navigation I am new to react native and i am trying to make screen which has two tabs and one drawer. For this i am using createTabnavigator inside createDrawerNavigator and this createDrawerNavigator inside createStackNavigator. I have enabled the swipeEnable but still the swipe gesture is not working for drawer but the tabs are working fine. Please help me to find a way to make this work.
Here is the set up of createDrawernavigator.
App.js
import React from "react";
import { TouchableOpacity } from "react-native";
import { connect } from "react-redux";
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
createMaterialTopTabNavigator
} from "react-navigation";
import Icon from "react-native-vector-icons/MaterialIcons";
import { DrawerActions } from "react-navigation-drawer";
import Login from "./modules/LoginPage/components/Form";
import NewComplaint from "./modules/newComplaint/components/Form";
import OpenTab from "./modules/homePage/components/OpenTab";
import ClosedTab from "./modules/homePage/components/CloseTab";
import complaintDetails from
"./modules/ComplaintDetail/components/Details";

const App = props =>
// eslint-disable-next-line react/prop-types
props.authentication.data.success ? (
<LoginRootStack />
 ) : (
 <LoggedOutRootStack />
 );

const Drawer = createDrawerNavigator(
{
  OpenComplaints: createMaterialTopTabNavigator(
  {
    Open: { screen: OpenTab },
    Closed: { screen: ClosedTab }
  },
  {
    order: ["Open", "Closed"],
    initialRouteName: "Open"
  }
),
ClosedComplaints: createMaterialTopTabNavigator(
  {
    Open: { screen: OpenTab },
    Closed: { screen: ClosedTab }
  },
  {
    order: ["Open", "Closed"],
    initialRouteName: "Closed"
  }
  )
 },
 {
 navigationOptions: ({ navigation }) => ({
  title: "Home",
  drawerLockMode: "unlocked",
  headerLeft: (
    <TouchableOpacity
      style={{ marginLeft: 10 }}
      onPress={() => {
        navigation.dispatch(DrawerActions.toggleDrawer());
      }}
    >
      <Icon name="menu" size={30} color="#fff" navigation={navigation}
    />
    </TouchableOpacity>
  ),
  headerRight: (
    <TouchableOpacity
      style={{ marginRight: 10 }}
      onPress={() => {
        navigation.navigate("newComplaint");
      }}
    >
      <Icon name="add" size={30} color="#fff" navigation={navigation} />
    </TouchableOpacity>
  ),
  headerStyle: {
    backgroundColor: "#2980b9"
  },
  headerTintColor: "#fff",
  headerTitleStyle: {
    fontWeight: "bold"
  }
}),
swipeEnabled: true,
contentOptions: {
  activeTintColor: "#2980b9"
 }
}
);

const LoggedOutStack = createStackNavigator(
 {
 Login: { screen: Login },
 Home: { screen: Drawer },
 newComplaint: { screen: NewComplaint },
 Details: { screen: complaintDetails }
 },
 {
 swipeEnabled: true,
initialRouteName: "Login",
headerMode: "none"
}
);

const LogggedInStack = createStackNavigator(
 {
 Login: { screen: Login },
 Home: { screen: Drawer },
 newComplaint: { screen: NewComplaint },
 Details: { screen: complaintDetails }
 },
 {
  swipeEnabled: true,
  initialRouteName: "Home"
 }
 );

 function mapStateToProps(state) {
 return {
 authentication: state.authentication
 };
 }

 export const LoginRootStack = createAppContainer(LogggedInStack);
 export const LoggedOutRootStack = createAppContainer(LoggedOutStack);

 export default connect(mapStateToProps)(App);

A: Put LoggedOutStack and LogggedInStack in switchStackNavigator and put that switchStackNavigator in createAppContainer.


text:
Q: Idea Live Template to Log Method Args I would like to be able to create a live template in Jetbrain's Idea that will log the method's arguments. Let's call it "larg". It would work like:
public void get(String one, String two) {
    larg<tab>

to create
public void get(String one, String two) {
    log.info("get: one = " + one + " two = " + two);

I'm fine with getting the method name in, but have not figured out how to pull in the method arguments. Any ideas?

A: I'm 4 years late, but the predefined template soutp pretty much does this using a groovyscript variable.
Here's the groovy script that does what you're looking for
groovyScript("'\"' + _1.collect { it + ' = [\" + ' + it + ' + \"]'}.join(', ') + '\"'", methodParameters())

A: Looks like it is not currently possible with a live template.
From the Jetbrain's forum:
There is no predefined live template function to do this for you automatically.
You can write a plugin that would provide such a function.

A: this is my groovy script
groovyScript("import com.intellij.psi.*;import com.intellij.psi.util.PsiTreeUtil; def file = PsiDocumentManager.getInstance(_editor.project).getPsiFile(_editor.document); PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(file, _editor.caretModel.offset, PsiMethod.class, false); PsiParameter[] parameters = method == null ? PsiParameter.EMPTY_ARRAY : method.parameterList.parameters; return parameters.size() == 0 ? '' : '\"' + method.name + ' : ' + parameters.collect { def prefix = it.name + ' = '; def type = it.type; return type instanceof PsiArrayType ? type.componentType instanceof PsiPrimitiveType ? prefix + '\" + java.util.Arrays.toString(' + it.name + ')' : prefix + '\" + java.util.Arrays.deepToString(' + it.name + ')' : prefix + '\" + ' + it.name }.join(' + \", ')", methodParameters())

A: In Android Studio in Kotlin I use this to log classname, methodname and parameters.
I use my name as tag to easily filter in logcat. I use these mainly for debugging, I don't commit these messages with my name.
Log.d("MYNAME", "$CLASS_NAME$:$METHOD_NAME$: $PARAMETERS$")
And then the parameters are defined as follows.
CLASS_NAME : kotlinClassName()
METHOD_NAME : kotlinFunctionName()
PARAMETERS : groovyScript("'' + _1.collect { it + ' = $' + it}.join(', ') ", functionParameters())
This would be the result if used in the main activity
 fun aFunctionWithParameters( first: Int, second: String, third: ArrayList<String>){
        Log.d("MYNAME", "MainActivity:aFunctionWithParameters: first = $first, second = $second, third = $third")
    }

I based my solution on Rob's answer and edited it to my needs.


text:
Q: Prove that MGF defined on an open set is infinitely differentiable I am doing an exercise in the book "Applied Stochastic Analysis" by E-Li-Vanden-Eijnden, and I meet this problem (on Page 26):

(Exercise 1.19) Prove that if the moment generating function $M_X(t)$ can be defined
on an open set $U$, then $M_X(t)\in C^{\infty}(U)$.

Here is my approach:
Use Taylor's expansion at $t=t_0$,
$$\frac{1}{t}\mathbb{E}[e^{(t_0+t)X}-e^{t_0X}]=\mathbb{E}[e^{t_0X}X]+o(t)\mathbb{E}[e^{t_0X}]$$
Let $t\to 0$,
$$\frac{d}{dt}M_X(0)=\mathbb{E}[e^{t_0X}X]$$
Repeat differentiation $n$ times,
$$\frac{d^n}{dt^n}M_X(0)=\mathbb{E}[e^{t_0X}X^n]$$
Since $n$ is arbitrary, as $n\to\infty$, we prove the claim.
Can anyone help me check whether my approach is valid? I'm not quite confident, since the exercise allows only on open sets. Alternative approaches are also fine. Thank you.
Edit:
OKay, I think I figure this out. Choose $U=(-\epsilon,\epsilon)$. For $|t|<\epsilon$,
$$\frac{|t|^n|X|^n}{n!}\leq e^{t|X|}\leq e^{tX}+e^{-tX}<\infty$$
and since
$$\left|\sum_{k=0}^{n}\frac{(tX)^k}{k!}\right|\leq\sum_{k=0}^{n}\frac{|tX|^k}{k!}\leq e^{|tX|}\leq e^{tX}+e^{-tX}$$
By dominated convergence theorem, $$M_X(t)=\mathbb{E}\left[\sum_{k=0}^{\infty}\frac{(tX)^k}{k!}\right]=\sum_{k=0}^{\infty}\frac{t^k}{k!}\mathbb{E}[X^k]$$
$M_X(t)$ coincides with the power series on $U=(-\epsilon,\epsilon)$, and hence it is infinitely differentiable on $U$, and $M_X^{(k)}(0)=\mathbb{E}[X^k]$.

A: Answer for the case $U=(-r,r)$:  First note that $Ee^{t|X|} \leq E(e^{tX}+e^{-tX}) <\infty$ for $0< t <r$.  Let us show that $M_X$ is differentiable. Using similar argumnets and induction we can show that it is infinitely differentiable. Let $|t|<r$ and choose $u$ with $|t|<u<r$. Consider $M_X'(t)=\lim_{h \to 0}  E{e^{tX}}\frac {e^{hX-1}} h$. By MVT we get $ |{e^{tX}}\frac {e^{hX-1}} h| \leq |X| e^{u|X|}$ provided $|h| <u-|t|$. If we show that $E|X|e^{u|X|} <\infty $ it follows by DCT that $M_X$ is differentiable are $t$ and $M_X'(t)=EXe^{tX}$. Now pick $v$ such that $u <v<r$ and note that there exists a finite  constant $C$ such that $|x|e^{u|x|} \leq Ce^{v|x|}$ for all real numbers $x$. It follows that $E|X|e^{u|X|} <\infty $ so we are done.


text:
Q: Alternate of Spring HandlerMethodSelector.selectMethods I was using Spring 4.2.x HandlerMethodSelector class - now migrating to Spring 5.1.x. Can anyone please help? how can we replace the below code in the latest Spring version?
final Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new MethodFilter()
    {
        @Override
        public boolean matches(final Method method)
        {
            return hasRequestMappingOverrideAnnotation(method);
        }
    });

A: HandlerMethodSelector replaced with MethodIntrospector

@deprecated as of Spring 4.2.3, in favor of the generalized and refined {@link MethodIntrospector}

You have similar method to use
 static Set<Method> selectMethods(Class<?> targetType, ReflectionUtils.MethodFilter methodFilter)

Select methods on the given target type based on a filter.


text:
Q: How to get nested Selects in a where_in clause in CodeIgniter's datamapper? I have a MySQL query that I've gotten to work in PhpMyAdmin/MySQL Workbench.
SELECT *
FROM (`medfacts`)
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
where title in (
 select medfacts.title from medfacts
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
 where categories_medfacts.category_id = 2
)
or title in (
 select medfacts.title from medfacts
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
 where categories_medfacts.category_id = 3
)

(The query gets all medfacts that are listed in the join table categories_medfacts with the given category IDs.)
I now need to transfer it to my CodeIgniter project in a way that allows my program to add as many Having clauses as needed. What I have so far generates the query mostly right.
function list_by_category($cat, $module) {
    /* Get a list of the Medfacts entries that have this category.         *
     */
    $this->db->join('categories_medfacts', 'categories_medfacts.medfact_id = medfacts.id');
    $this->where('medfacts.module_id', $module);
    /* If the category is an array, just get the articles that fall under all categories.
     * This shouldn't be more than a handful deep.
     */
    if (is_array($cat)) {
        foreach ($cat as $field => $value) {
            $this->where_in('title', "select medfacts.title from medfacts JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id` where categories_medfacts.category_id = {$value}");
        }
    } else {
        $this->where('categories_medfacts.category_id', $cat);
    }
    $this->select('medfacts.title');
    return $this->get();
}

However, I can't get it to not escape the nested Select statements, and end up with this:
SELECT `medfacts`.`title`
FROM (`medfacts`)
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
WHERE (
`medfacts`.`module_id` = '2'
AND `medfacts`.`title` IN ('select medfacts.title from medfacts JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id` where categories_medfacts.category_id = 2')
AND `medfacts`.`title` IN ('select medfacts.title from medfacts JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id` where categories_medfacts.category_id = 3')
 )
AND `medfacts`.`site_id` = 1

Notice the quotes around the nested select in the where in clause.
Is there a way to get Datamapper to not escape that nested select? Or, is there a better way to achieve the same goal? Or am I stuck writing the query myself?
I'm using CI 1.7.2 and Datamapper DMZ 1.7.1 (updating is currently out of the question) on PHP5 severs.
Edit: I am aware that a simple or where would return articles that match each where case. However, that's not what I need. I need only results that fall under all given categories. With my current setup, an or where returns too many results (includes ones that only fall under one of the listed categories), and and where doesn't return anything (nor would it ever, as the category_id can't both be "2" and "3").
Also, I found a JOIN, such as below also works in MySQL, but I can't translate it into CI, either (I didn't post it, because I thought the where in above was the cleaner method).
SELECT *
FROM (`medfacts`)
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
join (
    select medfacts.title, medfacts.id from medfacts
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
    where categories_medfacts.category_id = 2
)  m1
on m1.id = medfacts.id
 join (
    select medfacts.title, medfacts.id from medfacts
JOIN `categories_medfacts` ON `categories_medfacts`.`medfact_id` = `medfacts`.`id`
    where categories_medfacts.category_id = 3
) m2
on m2.id = medfacts.id
where `medfacts`.`module_id` = '2'
and medfacts.site_id = 1

A: there is only one way I found to perform subselects in CI - http://heybigname.com/2009/09/18/using-code-igniters-active-record-class-to-create-subqueries/
however, some time ago I have been warned by a very skilled programmer (my boss actually :D) that subselects are quite slow and performing multiple separate selects or trying to do a join instead (where possible) is much quicker... didn't have an opportunity to benchmark it, so take it just as a minor suggestion :)


text:
Q: Removing modsecurity rule via .htaccess I get a 500 Internal Server Error when trying to save a file with some text that may resemble an sql query. So ModSecurity is blocking it:
[client xxx.xxx.xxx.xxx] ModSecurity: Access denied with code 500 (phase 2). Pattern match "(insert[[:space:]]+into.+values|select.*from.+[a-z|A-Z|0-9]|select.+from|bulk[[:space:]]+insert|union.+select|convert.+\\\\(.*from)" at ARGS:description. [file "/usr/local/apache/conf/modsec2.user.conf"] [line "359"] [id "300016"] [rev "2"] [msg "Generic SQL injection protection"] [severity "CRITICAL"] [hostname "xxxxxxxxxxxxx.net"] [uri "/app/3/admin/modules/product/product_a.php"] [unique_id "TzvCxkPj2kkAAH4WkMwAAAAE"]

So I create an .htaccess file on the folder /app/3/admin/modules/product/
<IfModule mod_security.c>
SecFilterRemove 300015
SecFilterRemove 300016
</IfModule>

But this is not solving the issue either. I am still getting a 500 code with log entries in apache's log file.
Any idea why this may not be working?

A: Is it really the saving of the file that is the problem? I find it hard to imagine, seeing as that isn't Apache's jurisdiction at atll. Isn't it rather the query being in a query string that is causing trouble?
You might be able to circumvent that e.g. by base64 encoding the query (if the 33% size increase doesn't test the URL's size limits), or storing the query in a session variable and passing only a unique random key pointing to the variable.

Edit: if you're really transmitting live SQL queries that you later execute - don't do it. It's exactly the reason why this mod_security filter exists.
either way, phpMyAdmin, a database management tool, has the same problem: It transmits live queries for running. There is a number of posts dealing with phpMyAdmin and mod_security. This one suggests a number of other filter IDs to disable. (Ideally, you would do this only for the one file that needs to receive the POST data.)


text:
Q: Einstein Activity Capture: Emails are not shared on records I've got an issue with Einstein Activity Capture. All emails captured from collaborators who have standard permissions (meaning not the "view all data" privilege) aren't shared by default - despite the fact that in Setup, default sharing is turned on (in the Einstein Activity Capture) tab, and in their private email settings, sharing is turned on as well.
Am I missing something in the permission set possibly? Where would I start looking?
Thanks & much love from Germany,
Dominik

A: I've actually found the answer: https://success.salesforce.com/answers?id=9063A000000pokrQAA
Each user needs to switch their private Einstein Activity Capture settings to "Only Me" and then back to "Share with Everyone". Seems to be a glitch.


text:
Q: Rails association not working I don't even know where to start to explain my problem, so please bear with me :( !
I have two models; Product and Category - Product has_one Category and Category belongs_to Product
Product model
id
name
description
brand
merchant
price
image
link
category

Category model
id
name
product_id

Ok so now I'm looping through an XML feed create products like so:
Product.create(:name => node.xpath("./text/name/text()").inner_text.downcase,
               :description => node.xpath("./text/desc/text()").inner_text,
               :brand => node.xpath("./brand/text()").inner_text,
               :merchant => node.xpath("../@name").inner_text,
               :category => Category.find_by_name(node.xpath("./cat/text()").inner_text.downcase),
               :price => "£" + node.xpath("./price/btext()").inner_text)

This appears to run great, until I look at what it's produced in the database... Here's the output from both tables.
Products table(abridged version, contains 10,000+ records)
id: 1
....
....
....
category:     <---- empty for all 10,000+ records... err wtf? Surely should be a category ID or name
Categories table  (only contains 8 records, one for each category)
id: 1
name: socks
product_id: 10662 <---- err wtf?
id: 2
name: combinations
product_id: 10658 <---- err wtf?
id: 3
name: shoes
product_id: 9954 <---- err wtf?
id: 4
name: nightwear
product_id: 10653 <---- err wtf?
id: 5
name: hats
product_id: 10655 <---- err wtf?
id: 6
name: shorts
product_id: 10221 <---- err wtf?
id: 7
name: jeans
product_id: 9973 <---- err wtf?
id: 8
name: trainers
product_id: 8072 <---- err wtf?
To be honest I'm so confused, I'm not sure what I want to see anymore :-/
I just want the two tables to link together lol. Am I missing something fundamental here!?

A: Your relationship is backwards. If you want a product to be in a single category you need:
Product
belongs_to :category
Category
has_many :products

A: There are a couple of changes you need to make. Firstly, your model structure should look like this:

class Product
  belongs_to :category
end

class Category
  has_many :products
end

Secondly, your products table should have a category_id, not a category and your categories table should not have a product_id at all. Your code example should then run properly.

A: When you use has_one / belongs to, only one of the models ends up containing the id of the other.  In your case, since Category belongs_to Product, the categories table needs a product_id column, where it'll store the ID of the product it belongs to.
But if Product has_one Category (this also applies to has_many), it doesn't need a category_id column - Rails knows that to find the category (c) for a given product (p), it can just look through the categories table for a category where product_id == p.id.
From the code you posted, it looks like Rails is doing what it should - even though the relationship is accessible from both models, only the model that has the belongs_to directive has any relationship data stored in its table.  In fact, Rails is smart enough to know that when you specify the {:category => cat} option when creating a Product, it should actually change the categories table - and it does.  That's why you're seeing product_ids in your categories table, and nothing in your products table (and the column products.category doesn't even need to exist - the relationship will work fine without it).
With that said, I suspect that a Product should be able to belong to more than one Category, and , likewise, a Category should be able to contain more than one Product.  In that case, you'll want to use has_and_belongs_to_many in both models, and create the join table categories_products to connect them...
Hope this clears things up!


text:
Q: Hide linking errors when syntax errors are present Syntax errors in a model might cause false linking errors because the referenced element cannot be parsed. These false linking errors distract the user and makes it very hard to diagnose the root cause. What we want is to hide XtextLinkingDiagnostic when XtextSyntaxDiagnostic is present in the model, once the syntax errors are fixed the linking errors should be displayed as usual.
I didn't find any standard way to do it in the Xtext documentation. Thus, I went ahead and implemented a custom IAcceptor in ResourceValidatorImpl#createAcceptor() which removes linking errors from the list if it contains syntax errors. It works well, but I wonder if there is a standard/better way to do it than overriding ResourceValidator.
Thanks.

A: What do you think about displaying linking problems as warnings instead of errors. Your syntax errors will remain red and easy to find in the ressource, whereas linking errors will be in yellow as they are less important problems.
You only have to bind a custom LinkingDiagnosticMessageProvider:
public Class<? extends ILinkingDiagnosticMessageProvider> bindILinkingDiagnosticMessageProvider() {
    return CustomLinkingDiagnosticMessageProvider.class;
}

Then you can implement it like this:
public class CustomLinkingDiagnosticMessageProvider extends LinkingDiagnosticMessageProvider {
    @Override
    public DiagnosticMessage getUnresolvedProxyMessage(ILinkingDiagnosticContext context) {
        DiagnosticMessage diagnosticMessage = super.getUnresolvedProxyMessage(context);
        return new DiagnosticMessage(diagnosticMessage.getMessage(),
                Severity.WARNING,
                diagnosticMessage.getIssueCode(),
                diagnosticMessage.getIssueData());
    }
}


text:
Q: Jquery UI Tooltip is possible to have a icon and a title on it. At the examples are only simple texts At http://wiki.jqueryui.com/w/page/12138112/Tooltip
there is an example for M1 of a Tooltip with an icon and a title.
How can you do this with current Jquery UI Tooltip?

A: You can do this by adding html tags inside tooltip using "content" option. Check this JQFAQ.com topic which will explain you how to do this.


text:
Q: Height oscillations in orbit induced from lunar gravity I am trying to numerically solve the orbit of a space probe around the moon in a non-spherical gravitational field .
$
\Large
\begin{align}
\frac{d^{2} x}{dt^2} = - \frac{G M x}{(x^2 + y^2)^{3/2}}
- \frac{q\ G M x^\prime}{(x^{^\prime2} + y^{^\prime2})^{3/2}}
\end{align}
$
$
\Large
\begin{align}
\frac{d^{2} y}{dt^2} = - \frac{G M y}{(x^2 + y^2)^{3/2}}
- \frac{q\ G M y^\prime}{(x^{^\prime2} + y^{^\prime2})^{3/2}}
\end{align}
$
$
\Large
\begin{align}
x^\prime = x + 0.8\ R \cos \left( \frac{2 \pi t}{T_{Moon}} \right)
\end{align}
$
$
\Large
\begin{align}
y^\prime = y + 0.8\ R \sin \left( \frac{2 \pi t}{T_{Moon}} \right)
\end{align}
$
where q = 0.00025 and T_moon = 27.3
I have tried to implement this with the velocity Verlet algorithm and have obtained a height verus time graph for the orbit. The space probe is supposed to hit the lunar surface at one point and here is the graph of the height versus time until the probe collides with the surface :

Here are the height oscillations versus time when I set the initial height so that the probe does not collide with the lunar surface after many orbits, compared with the previous result:

Is this physically correct with the equations of motion given above? Would this really happen in reality? How can I interpret this result? Here is the code I used in python to generate this. I used the velocity verlet algorithm to generate the numerical solution to the orbit and I am not sure if the implementation is correct, any comments on my implementation are very welcome.
    from IPython.display import HTML
    import matplotlib.pyplot as plt
    from matplotlib import animation, rc
    import numpy as np
    from scipy import integrate, optimize
    import time

    plt.rcParams['figure.figsize'] = (10, 6)
    plt.rcParams['font.size'] = 16

    # Gravitational constant
    gg     = 6.67408e-11 # m^3 s^-1 kg^-2
    # Lunar mass
    mass   = 7.342e22 # kg
    # Lunar radius
    radius = 1738000 # m
    # 1 day in seconds
    day    = 3600*24 # seconds

    ### Initial positions and velocities at t=0
    rs = [1842280, 0] # m
    vs = [0, 1634]    # m/s
    N=10**5
    t_moon = 27.3*24*3600
    ts = np.linspace(0,t_moon, N-1)
    q = 0.00025

    rs = np.array([1842280, 0]) # m
    vs = np.array([0, 1634])    # m/s
    distance = np.array([(np.linalg.norm(rs) - radius),0])
    for i in ts:
        x_prime = rs[0] + 0.8*radius*np.cos((2*np.pi*i)/t_moon)
        y_prime = rs[1] + 0.8*radius*np.sin((2*np.pi*i)/t_moon)
        r_primes = np.array([x_prime,y_prime])
        acs = np.array([-((gg*mass*rs[0])/(np.linalg.norm(rs)**3))-((q*(gg*mass*r_primes[0]))/(np.linalg.norm(r_primes)**3)),-((gg*mass*rs[1])/(np.linalg.norm(rs)**3))-((q*(gg*mass*r_primes[1]))/(np.linalg.norm(r_primes)**3))])
        rs = rs + vs*ts[1] + acs*((ts[1]**2)/2)
        next_acs = np.array([-((gg*mass*rs[0])/(np.linalg.norm(rs)**3))-((q*(gg*mass*r_primes[0]))/(np.linalg.norm(r_primes)**3)),-((gg*mass*rs[1])/(np.linalg.norm(rs)**3))-((q*(gg*mass*r_primes[1]))/(np.linalg.norm(r_primes)**3))])
        vs = vs + ((next_acs + acs)*ts[1])/2
        pos = np.c_[pos,rs]
        distance = np.c_[distance,[(np.linalg.norm(rs)-radius),i+ts[1]]]
        if np.linalg.norm(rs) <= radius:
            print("BANG")
            print("time is: ", ts[len(pos[0,:])])
            break
    plt.xlabel("time(hrs)")
    plt.ylabel("height(km)")
   # plt.plot(pos[0,:], pos[1,:])

    plt.plot(distance[1,:]/3600,distance[0,:]/(10**3))

A: These are my equations with $(q=1)$
$${\ddot{x}}+1/2\,{\frac {MGx}{ \left( {x}^{2}+{y}^{2} \right) ^{3/2}}}+1
/4\,MG \left( 2\,x+2\,aR\cos \left( 2\,{\frac {\pi \,\tau}{T_{{M}}}}
 \right)  \right)  \left(  \left( x+aR\cos \left( 2\,{\frac {\pi \,
\tau}{T_{{M}}}} \right)  \right) ^{2}+ \left( y+aR\sin \left( 2\,{
\frac {\pi \,\tau}{T_{{M}}}} \right)  \right) ^{2} \right) ^{-3/2}-2\,
aR\cos \left( 2\,{\frac {\pi \,\tau}{T_{{M}}}} \right) {\pi }^{2}{T_{{
M}}}^{-2}=0
$$
$${\ddot{y}}+1/2\,{\frac {MGy}{ \left( {x}^{2}+{y}^{2} \right) ^{3/2}}}+1
/4\,MG \left( 2\,y+2\,aR\sin \left( 2\,{\frac {\pi \,\tau}{T_{{M}}}}
 \right)  \right)  \left(  \left( x+aR\cos \left( 2\,{\frac {\pi \,
\tau}{T_{{M}}}} \right)  \right) ^{2}+ \left( y+aR\sin \left( 2\,{
\frac {\pi \,\tau}{T_{{M}}}} \right)  \right) ^{2} \right) ^{-3/2}-2\,
aR\sin \left( 2\,{\frac {\pi \,\tau}{T_{{M}}}} \right) {\pi }^{2}{T_{{
M}}}^{-2}
=0$$
with your data I got this result simulation time 32000 [S]


text:
Q: Create custom Audio/Video chat server using WebRTC for iOS? I have been studying WebRTC from last 2 days but couldn't understand how to develop and stand up a server based on WebRTC for iOS.
I really don't want to use any 3rd party Audio/Video chat service providers in my application even if they are WebRTC based. I want to create my own WebRTC based custom Audio/Video chat.
I just need a startup guide for developing WebRTC based chat server.

A: Couple of things:

*

*You will have to work with the NativeAPI and compile for iOS, this tutorial should help, this is for the iOS client side only.

*If you chat is only one-to-one a simple websocket or socket.io with node.js for your signalling server should be simple enough

*If you want numerous parties in the same chat, you will either have to handle all the individual connections(numerous individual peer connections for each device connecting) or implement a type of MCU, licode is an EXAMPLE of such
Those links are just examples of how people have done similar things before, you should not have to utilize their libraries or their solutions. But, you WILL have to use the WebRTC Native API, handle numerous peerconnections for each client(or create your own MCU server), and handle the signalling between each client(for connection start up and tear down).

A: You can also try Icelink api provided by Frozen mountain
They have provided free trials for iOS, android , web client, windows phone.
Also they have provided their own turn and stun servers which can be only used in windows server 2013. Overall library is very well documented and easy to use.
You need to register yourself to download the api, which is free of cost.
Hope it meet your requirements.
Good luck


text:
Q: How can I test(or run) Intellij IDEA run configuration in CI? I have some configurations in IDEA those saved in the project as XML files and I want them to be tested/verified in CI. I want to test them to make sure they could be running and will run successfully.
How can I do that?
Addition 1: For example, let's see this XML:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="CurrenciesApp" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot" nameIsGenerated="true">
    <module name="sba-currencies-service" />
    <extension name="coverage">
      <pattern>
        <option name="PATTERN" value="aero.s7.*" />
        <option name="ENABLED" value="true" />
      </pattern>
    </extension>
    <option name="SPRING_BOOT_MAIN_CLASS" value="aero.s7.CurrenciesApp" />
    <option name="ALTERNATIVE_JRE_PATH" />
    <method v="2">
      <option name="Make" enabled="true" />
    </method>
  </configuration>
</component>

Addition 2: I'm stuck now in searching for some Maven plugin that can run those configurations.


text:
Q: Get-ADUser - searching for expired account. Using variables in command I am currently working on a Powershell GUI script to help my team easier find accounts with expired passwords, disabled accounts etc and to output these to a CSV. It revolves almost entirely around the "Get-ADUser" command. So far almost everything has worked, bar finding accounts with expired passwords.
I've researched this a lot already but there seems to be no easy way of finding expired accounts using Get-ADUser. I know I can use Search-ADAccount instead but it would be very awkward to do so (as I would need to re-write a lot of code).
Get-Aduser -Properties * -Filter {PasswordExpired -eq $true} just draws a blank.
I've found a partial solution over at https://serverfault.com/questions/805526/get-aduser-password-expired-filter-not-working-correctly/805611
For example,
Get-ADUser -Properties * -Filter * | ? {$_.PasswordExpired -eq $True -and $_.Enabled -eq $true} | Select-Object name, enabled | Export-Csv "C:\report.csv" -NoTypeInformation
works just fine but if I try to assign the 'middle' of the command i.e
{$_.PasswordExpired -eq $True -and $_.Enabled -eq $true}
to a variable and then substitute it into the command I either get an error, a list of all those in my AD or nobody at all. The rational for substituting in a variable is to allow for the possible account statuses (that the user can choose from by selecting a radio button).
I've tried the various permutations of double and single quotes, including and not including curly brackets etc but Powershell will not give me a break!
Thanks!

A: The Get-ADUser cmdlet exposes the PasswordExpired extended property, which is a boolean indicating if the password is expired. It is based on the msDS-User-Account-Control-Computed attribute. However, you cannot filter with this property.
This would mean you can check the UF_PASSWORD_EXPIRED bit on that property:
Get-ADUser -Filter "Enabled -eq 'True'" -Properties 'msDS-User-Account-Control-Computed' |
    Where-Object {($_.'msDS-User-Account-Control-Computed' -band  0x800000) -eq 0x800000} |    # UF_PASSWORD_EXPIRED --> 0x800000 = 8388608
    Select-Object Name, Enabled | Export-Csv "C:\report.csv" -NoTypeInformation

You can speed up the above by extending the filter to rule out users with PasswordNeverExpires and PasswordNotRequired both $false:
$filter = "Enabled -eq 'True' -and PasswordNeverExpires -eq 'False' -and PasswordNotRequired -eq 'False'"
Get-ADUser -Filter $filter -Properties PasswordNeverExpires, PasswordNotRequired, 'msDS-User-Account-Control-Computed' |
    Where-Object {($_.'msDS-User-Account-Control-Computed' -band 0x800000) -eq 0x800000} |    # UF_PASSWORD_EXPIRED --> 0x800000 = 8388608
    Select-Object Name, Enabled | Export-Csv "C:\report.csv" -NoTypeInformation

A: I reckon I've found a solution over on Stack Exchange.
See https://serverfault.com/questions/723217/find-out-if-password-expired-or-when-it-expires-for-user-in-a-specific-ou
Early tests suggest it works.


text:
Q: Android Recyclerview : change row from linear to grid on button click On button click I want to change list view to gridview as on shopping-cart pages but my layout looks like link shown below.
//For displaying the row as linear list view
case R.id.ivGrid:
    ivList.setVisibility(View.VISIBLE);
    ivGrid.setVisibility(View.GONE);
    LinearLayoutManager llm = new LinearLayoutManager(context);
    rcvProducts.setLayoutManager(llm);
    break;

//For displaying the row as gridview
case R.id.ivList:
    ivList.setVisibility(View.GONE);
    ivGrid.setVisibility(View.VISIBLE);
    GridLayoutManager glm = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL, false);
    rcvProducts.setLayoutManager(glm);
    break;

GRIDview
LISTview

A: Just use a GridLayoutManager and change the span count from 1 to 2 and back again.
view.setOnClickListener(new View.OnClickListener(){
    public void onClick(View view){
        GridLayoutManager layoutManager = (GridLayoutManager) grid.getLayoutManger();
        layoutMananger.setSpanCount(layoutManager.getSpanCount() == 2 ? 1 : 2);
    }
})

A: *

*Maintain 2 adapters, one for ListView and one for GridView.

*On button click, change the adapter to RecyclerView.

*Listview.setAdapter(gridAdapter) (or) ListView.setAdapter(listAdapter)


text:
Q: Resize bootstrap columns by dragging them My angular application has a container and I am generating dynamic columns (via dynamic components), these columns have bootstrap classes. My columns can be upto 6 max and 1 min. On changing number of columns from 1->6 or 6->1,6->3 etc I update all dynamic column's classes so total sum is always 12.
I am required to resize these columns by dragging from one side and to update adjacent column's classes so total is never exceeds 12. I have searched quite few things like jQuery-ui  dragging and other fiddles but not got any good approach either they are very much in jQuery way or none.
Any help would be highly appreciated in form of suggestion,code link,article or any direction.
PS: I have came across this e.g. codepen for bootstrap resizing but it is very jQuery way and I am looking something similar in angular 5.

This another example I have came across, that it simply updates it's neighbour columns on dragging e.g. if 3 columns  [3,4,5] so on dragging first column it will go to max of [6,1,5] i.e. it will not go further changing to 3rd column [7,1,4]

and my container columns look like

A: I am answering this question because I just got a work around close to what I want to achieve and helpful to someone in someway, but still it is exact solution of the example that I am following.
This fiddle gave me a general idea, how can be achieved. So I calculated the mouse X-axis on mousedown event on element and mouseup event on document where I get final X-axis, then I calculates the direction (left or right) and updates the corresponding pair of bootstrap classes. e.g. having 3 columns [3,4,5] so on dragging first column towards right direction I updates it too [4,3,5]
But it still lags the smoothness or snapping (after certain x-axis covered then updates the column)


text:
Q: Limiting the drawing to a rectangle in OpenGLES I need to limit the drawing of an object to a rectangle. I can't just change the viewport to match the rectangle becouse the ModelView matrix (that should change the rectangle, but not the content) may not be identity. A solution that would work is to draw to a FBO that match the rectangle, then draw the FBO to the screen, but it seems to slow. Is there any better option to do that?

A: If I understood you correctly, glScissor should be the function you are looking for. It crops the rendering to a selected sub-rectangle of the viewport. This does not modify the viewport. So the objects cover the same size on the screen, it just prevents you from drawing any pixels outside of the scissor region. If this is not what you want and you want the sub-rectangle to contain the whole scene and thus your objects to shrink, then changing the viewport is the solution of choice.
EDIT: If you want the rectangle to be transformable and especially rotatable (and therefore not a rectangle anymore on the screen), then rendering into an FBO and using this as texture on a quad is probably the best solution. Otherwise you could probably also just modify the vertex coordinates after projection, thus multiplying the transformation matrix of the target rectangle with the projection matrix and using this as new projection matrix, but I'm not completely sure about that (but at least something similar should do it.


text:
Q: jQuery multiple class and nth-child I have a table which has multiple classes.

One
Another
Yet another
Yet another
Four

One
Another
Yet another
Yet another
Four

One
Another
Yet another
Yet another
Four

What I want is to set the first text from the every tr which contain the td has class 'one', no mather if another class is added.
I've tried with a classic example, but it doesn't work:
        var i=0;
   $(".one:nth-child(1)").each(function() {
    temp[i] = $(this).text;
    console.log("Result: "+temp[i]);
        i++;
     });

But this doesn't work.

A: You need to use:
$("tr td.one:first-child").each(function(i) {
  temp[i] = $(this).text();
  console.log("Result: "+temp[i]);
});

Working Demo


text:
Q: Adding non-centered text shifts centered elements After putting a centered header, I add a non-centered output with JS. After the output is produced, the header shifts a bit left. What can be done to tackle this problem?

let output = [];

function spit() {
  for (let i = 0; i < 100; i++) {
    output.push(i);
  }
  document.getElementById("output").innerHTML =
    output.join("
");
}
.header {
  background-color: lightgray;
  border: none;
  color: black;
  padding: 17px 25px;
  display: block;
  text-align: center;
  font-size: 36px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}

  Testing Page

<button style="font-size:20pt;height:35pt" onclick="spit()">
         Press me!
</button>

A: One crazy solution might be to set you body height to the view port height, that way you start off with a scroll, avoiding the shift when the button gets pressed.

let output = [];

function spit() {
  for (let i = 0; i < 100; i++) {
    output.push(i);
  }
  document.getElementById("output").innerHTML =
    output.join("
");
}
body {
  min-height: 100vh;
}

.header {
  background-color: lightgray;
  border: none;
  color: black;
  padding: 17px 25px;
  display: block;
  text-align: center;
  font-size: 36px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}

  Testing Page

<button style="font-size:20pt;height:35pt" onclick="spit()">
         Press me!
</button>

A: I added a universal { margin:0; padding:0;} to your css code. The code did seem to be centered but I think the margin of -50 (that's being created by the auto margin ) is throwing off the look.

let output = [];

function spit() {
  for (let i = 0; i < 100; i++) {
    output.push(i);
  }
  document.getElementById("output").innerHTML =
    output.join("
");
}
* {
  margin: 0px; padding:0px;
}

button {
  /*margin-left:15px;*/
  margin-top:7px;
  font-size: 20pt;
  height: 35pt;
}

.header {
  background-color: lightgray;
 /* border: 15px solid white;*/ /*use the commented props if you still want the "indented" effect" */
  color: black;
  padding: 17px 25px;
  display: block;
  text-align: center;
  font-size: 36px;
  width: 100%;
  margin-right:auto;
  margin-left:auto;
}

  Testing Page

<button onclick="spit()">
         Press me!
</button>

A: IF you don't want the h1 to shift due to the scrollbar, you would have to calculate, using css calc() (and maybe some other things too), 50vw - (widthOfH1/2).  This works because the vw unit (viewport width) is not affected by the scrollbar.
One way for the scrollbar to not affect the centering of the h1 would be to use JQuery.
$(#dictName).style.marginLeft = 'calc(50vw -'+(this.width/2)+'px)';

I haven't tested this so I'm not 100% sure if it will work, but please tell me if it does or doesn't.  You may need to rerun this code when the button is pressed.

A: After some googling it seems I found the easiest way to solve this problem here, on SO:
How to prevent scrollbar from repositioning web page?
html {
  overflow-y: scroll;
}

Probably, the question should be closed as duplicate, but I don't have enough reputation to do it.


text:
Q: Why am I able to upload to AWS S3 from my localhost, but not from my AWS Elastic BeanStalk instance? I'm using AWS Credentials* to connect to my AWS S3.
final AmazonS3 s3 = new AmazonS3Client(
                  new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey*",
                      "secretKey")));
              s3.setRegion(Region.US_West.toAWSRegion());
              s3.setEndpoint("s3-us-west-1.amazonaws.com");

From my localhost, I'm able to upload image and since I have versioning enabled, I get versionId back for following line.
versionId = s3.putObject(new PutObjectRequest("bucketName", name, convFile)).getVersionId();

PS 3: Above piece of code is wrapped in a try-catch block and the catch block prints this
 You failed to upload fileName => fileName.jpeg (Permission denied)

But if I execute the same code from my ElasticBeanStalk, I get versionId=null and the image is not uploaded to S3.
I don't see credentials exception.

*

*
*

*When I searched the accessKey in Users(under IAM), I realized its not assigned to any user.

After reading all docs, I created two users.
One under a group which I created, another without a group.
I used accessKey of those users and still I'm not able to uploaded image to S3.
This is how my bucket policy looks like
After creating the two users
{
    "Version": "2012-10-17",
    "Id": "Policy1",
    "Statement": [
        {
            "Sid": "Stmt1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::someNumnber:user/username"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::bucketName"
        }
    ]
}

Before creating two users (and the following set up was in place when localhost successfully uploads image to S3)
{
    "Version": "2012-10-17",
    "Id": "Policy15",
    "Statement": [
        {
            "Sid": "Stmt1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::bcktName",
                "arn:aws:s3:::bcktName/*"
            ]
        }
    ]
}

I'm totally struck on this issue for 4 evenings.
Please help me.
I don't use boto or any other stuff.
Its a straight forward war file uploaded to tomcat, which has to upload images to S3. It works in localhost, but not in S3.
PS: This is how my CORS configuration look
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>20000</MaxAgeSeconds>
    <ExposeHeader>ETag</ExposeHeader>
    <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
    <ExposeHeader>x-amz-request-id</ExposeHeader>
    <ExposeHeader>x-amz-id-2</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

PS 2:
Should I do anything in Access Control list? As of now, I see the owner account is same as username of my entire AWS. I think The access key and secret key that works from local also related to owner account.

A: check your AWSAccessKey and AWSSecretKey in web config file. Aws API uses these credentials to login into your s3.
this same issue appeared to me as well, I solved it by doing this.
Hope that this would help anybody.


text:
Q: Puppet Master Server Fails to Start Out of No Where I've search around and have not found an answer that worked so I thought I would try to see if there are any Puppet Masters out there that can guide me.
Seemingly out of no where my Puppet Master server services are simply failing to start and I can't figure out why.
I did note that the puppet user had vanished (no sure why yet)
I recreated the user which cleared the error I was getting that the user was missing.
Now when I issue
systemctl start puppetserver.service
I get
Job for puppetserver.service failed because the control process exited with error code. See "systemctl status puppetserver.service" and "journalctl -xe" for details.
The status shows
puppetserver.service - LSB: puppetserver

   Loaded: loaded (/etc/init.d/puppetserver; bad; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2018-05-22 09:41:53 MDT; 29s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 4157 ExecStart=/etc/init.d/puppetserver start (code=exited, status=1/FAILURE)
May 22 09:41:53 oraws-puppet1 systemd[1]: Starting LSB: puppetserver...
May 22 09:41:53 oraws-puppet1 systemd[1]: puppetserver.service: Control process exited, code=exited status=1
May 22 09:41:53 oraws-puppet1 systemd[1]: Failed to start LSB: puppetserver.
May 22 09:41:53 oraws-puppet1 systemd[1]: puppetserver.service: Unit entered failed state.
May 22 09:41:53 oraws-puppet1 systemd[1]: puppetserver.service: Failed with result exit-code.

The system us Ubuntu 16.04. 16gb of mem. Dedicated server so 10gb is given to Java.
Any help would be appreciated!


text:
Q: Building Angular 2 App using angular-cli and deploying I have an angular 2 project which I am trying to deploy on a remote iis server. On my local machine the app runs fine. There are absolutely no problems regarding anything.
I am building it for production mode using
ng build --prod

I am copying contents of dist folder into the folder on my server. Now this is the first time I am deploying and there is no one to guide me. When I go to the website url it takes a long time to load compared to before(when i didn't deploy it). Also when I go to a page and refresh I get 404 Error.
Now I have seen both these links
Angular 2 CLI App throwing 404 errors once deployed
and
Refresh page got 404: only happen when using /dist folder
But if someone could elaborate what exactly I have to do to fix it and make the loading faster(there is no problem with code it is just the method of deployment) that would be really helpful
package.json

{
  "name": "ofweb",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve --host 0.0.0.0 --port 6363 --live-reload-port 43453",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.1",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^4.0.0-alpha.2",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "fullcalendar": "^3.3.0",
    "jquery": "^3.1.1",
    "moment": "^2.18.1",
    "primeng": "^4.0.0-rc.2",
    "primeui": "^4.1.15",
    "reflect-metadata": "^0.1.9",
    "rxjs": "^5.1.0",
    "systemjs": "^0.20.2",
    "ts-helpers": "^1.1.2",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0",
    "canonical-path": "^0.0.2",
    "concurrently": "^3.1.0",
    "http-server": "^0.9.0",
    "karma-htmlfile-reporter": "^0.2.2",
    "karma-remap-istanbul": "^0.2.1",
    "lite-server": "^2.2.2",
    "lodash": "^4.17.4",
    "rimraf": "^2.5.4",
    "typings": "^2.1.0"
  }
}

Server Log File Error

2017-04-24 07:35:38 104.245.36.179 GET /admin/organizations - 80 - 122.175.232.166 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36 - 404 0 2 349

A: I can't speak about the slow performance, but the '404 on refresh' issue is because of missing web server configuration.
When you try to load your default route (of /) from the server, your web server will interpret that as a request for index.html and send index.html and your Angular app will load. If you then navigate to some route (eg. /mystuff), the Angular router will take control and update the URL properly and navigate you to the correct component. If however, you then refresh, the web server will see the request for /mystuff and try to find the corresponding file, which won't exist - hence the 404.
The solution is to configure your web server to redirect all requests for files it can't find to your index.html.
See the docs for more information on how to do so for IIS.