text:
Q: How to index a cell from a matrix in Excel I am trying to find out how to choose the right diameter and number of rebars to the desired Area. I can find the right value from the Matrix using the MIN(IF(C9:L17>C9,L17:B6)) function or the SMALL(IF(C9:L17>C9,L17:B6),1), but can't index it to it's corresponding diameter and Number of rebar. The answer can be seperate with just the diameter or the Number of rebar but if it is possible I would like to have the answer like this format [Number of Rebar]Ø[Diameter].
As a second question. With the function SMALL i can find the second or third nearest value to my desired area. If the Diameter too small the function should choose the bigger Diameter. How can I impliment this idea to the whole function with index?
Example:
from a desired area of 7,8 cm2 [C3] there is 7,85cm2 [L10] chosen and the final answer for it is 10Ø10 [Number of Rebar]Ø[Diameter]

A: Since the value 7,8539 etc, is being looked up from the table, it will be an exact match, so you can use a formula like this to find the row:
=MIN(IF(C9:L17=J30,C8:L8))

and the column with
=MIN(IF(C9:L17=J30,B9:B17))

You can combine the two values in a text string.
=MIN(IF(C9:L17=J30,B9:B17)) & "Ø" & MIN(IF(C9:L17=J30,C8:L8))

Edit: you can use a helper cell to arrive at the lookup number, like the formula you use to arrive at the value in J30, or you can nest that formula.
So, if J30 has the formula =MIN(IF(C9:L17>C3,C9:L17)), then you can also use this all-in-one formula to find the row:
=MIN(IF(C9:L17=MIN(IF(C9:L17>C3,C9:L17)),C8:L8))

and for the column:
=MIN(IF(C9:L17=MIN(IF(C9:L17>C3,C9:L17)),B9:B17))


text:
Q: Delete right node of right subtree of binary search tree (C) I am working on a C binary search tree library and I'm trying to write a function that will delete the right node of the tree subtree. Here's the struct of my tree:
struct Node {
    int value;
    struct Node *left;
    struct Node *right;
};

typedef struct Node TNode;
typedef struct Node *binary_tree;

The tree is created like this:
binary_tree NewBinaryTree(int value_root) {
    binary_tree newRoot = malloc(sizeof(TNode));
    if (newRoot) {
        newRoot->value = value_root;
        newRoot->left = NULL;
        newRoot->right = NULL;
    }
    return newRoot;
}

Adding element to it:
void Insert(binary_tree *tree, int val) {
    if (*tree == NULL) {
        *tree = (binary_tree)malloc(sizeof(TNode));
        (*tree)->value = val;
        (*tree)->left = NULL;
        (*tree)->right = NULL;
    } else {
        if (val < (*tree)->value) {
            Insert(&(*tree)->left, val);
        } else {
            Insert(&(*tree)->right, val);
        }
    }
}

The function I wrote to delete the right node of the subtree is like this:
void delrightsubtree(binary_tree *tree){

        if( (*tree)->value!=NULL )

        {
                free(&(*tree)->right);
                delrightsubtree( &(*tree)->right);
        }
        else
        {
            printf("end");
        }
    }

However this function does not seem to work because it crash when I call this function(after adding multiple element to the tree). I don't really know how to do this.
Thank you!

A: You probably want to implement a recursive deletion method (like your insert method does).  Right now it looks like you're calling free on a single node, which isn't going to release any of the resources it's attached to (i.e. its children).  Instead, think about traversing the part of the tree that you want to delete and setting the appropriate values to NULL.

A: You'll simply call recursive delete method until you reach the end (there is no next point) then you just free everything you need and set to NULL things that suppose to be set to null.

redpajama_set_name: RedPajamaStackExchange


text:
Q: couchbase cluster document not replicating but splitting up I've set up a couchbase cluster with 2 nodes containing 300k docs on 4 buckets. the option replicas is forced to 1 as there are only 2 machines.
But documents are splitted half in one node half in the other, I need to have double copy of each document so if a node goes down the other one che still supply all data to my app.
Is there a setting I missed in creating the cluster?
can I still set the cluster to replicate all documents?
I hope someone can help.
thanks
PS: I'm using couchbase community 4.5
UPDATE:
I add screenshots of cluster web interface and cbstast output:
the following is the state with one node only

next the one with both node up:

then cbstats results on both node when both are up and running:

AS you can see with only one node there are half items displayed. Does it mean that the other half resides as replicas but are not shown???
can I still run consistenly my app with only one node???
UPDATE:
I had to click fail-over manually to see replicas become active on the remaining node. As with just two cluster auto fail-over is disabled!!!

A: Couchbase Server will partition or shard the documents across the two nodes, as you observed.  It will also place replicas on those nodes, based on your one-replica configuration.
To access a replica, you must use one of the Client SDKs.
For example, this Java code will attempt to retrieve a replica (getFromReplica("id", ReplicaMode.ALL)) if the active document retrieval fails (get("id")).
bucket.async()
    .get("id")
    .onErrorResumeNext(bucket.async().getFromReplica("id", ReplicaMode.ALL))
    .subscribe();

The ReplicaMode.ALL tells Couchbase to try all nodes with replicas and the active node.

A: So what was happening with only two nodes in the cluster was that auto fail-over didn't start automatically as specified here:
https://developer.couchbase.com/documentation/server/current/clustersetup/automatic-failover.html
this means data replicas where not activated in the remaining node unless fail-over was triggerd manullay.
The best thing is to have more than TWO nodes in the cluster before going in production.
To be honest I should have ridden documentation very carefully before asking any question.
thanks Jeff Kurtz for your help, you pushed me towards the solution. (the understanding of how couchbase replicas policy works).


text:
Q: ThreeJS world unit to pixel conversion Is there a way compute the ratio between world unit and pixels in ThreeJS ? I need to determine how many units apart my objects need to be in order to be rendered 1 pixel apart on the screen.
The camera is looking at the (x,y) plane from a (0, 0, 10) coordinate, and objects are drawn in 2D on the (x,y) plane at z=0.
<Canvas gl={{ alpha: true, antialias: true }} camera={{ position: [0, 0, 10] }}>

I cannot seem to figure out what the maths are or if there is any function that does it already...
I'm thinking I might have to compare the size of the canvas in pixels and world units, but I dont know how to get that either. There's also this raycasting solution, but surely there has to be a way to just compute it, no ?


text:
Q: What is the correct syntax of MIPS instruction sll? Should the shift amount be an immediate value, or a value stored in a register? Does both work?
I've had different websites tell me different things and am confused.
Based on my research the sll (shift left logical) instruction should be used like this:
  sll $d, $t, h

Which makes $d = $t shifted left h times.
I've been told that h should be a immediate value, but I was wondering if a register could be used as the third argument, and the value inside that register used as the shift amount. Would that also work?

A: You are correct.
sll is specific in that it is a R-format instruction where only two registers are used, rd and rs (destination and source), and the shamt field is a immediate value (a constant).
There is another instruction sllv which uses a third register where you specify shift by variable (the register).

A: Let me clear the point Shift left logical in MIPS 32 bit has following syntax:
SLL destination, Target, Shift amount(Should be immediate value)
Where as in 8086 if we want shift amount more than 1 we have to use a register to store the value of shift amount!


text:
Q: Proving $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$ I am trying to show $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$ using the Cantor Bernstein method. Here is my proof so far:
Let $f: \mathbb{R}\to\mathbb{R}^\mathbb{N}$ be defined as for each $r_n\in\mathbb{R}$ where $n\in\mathbb{N}$, $f(r_n)=(r_n,0,0,...)$. Thus, we have an injection from $\mathbb{R}$ to $\mathbb{R}^\mathbb{N}$. (For me, $0$ is in the natural numbers.)
Now, for the other direction, let $g:\mathbb{R}^\mathbb{N}\to\mathbb{R}$ be defined as follows. Let $(r_0,r_1,...,r_n,...)\in\mathbb{R}^\mathbb{N}$ where $r_n\in\mathbb{R}$ and let $r_n=Z_n.a_{0,n}a_{1,n}a_{2,n}...$ be the unique corresponding decimal expansion where $n\in\mathbb{N}$,  $Z\in\mathbb{Z}$, $0\leq a_{n,n}\leq 9$, and the sequence does not end in infinitely many 9's.
Consider the list:
$r_0=r_n=Z_0.a_{0,0}a_{1,0}a_{2,0}...$
$r_1=r_n=Z_1.a_{0,1}a_{1,1}a_{2,1}...$
$r_2=r_n=Z_2.a_{0,2}a_{1,2}a_{2,2}...$
Then, let $r=0.a_{0,0}a_{1,0}a_{0,1}a_{0,2}a_{1,1}a_{2,0}...\in\mathbb{R}$.
So, $g((r_0,r_1,...,r_n,...))= r$.
Then, we have an injection from $\mathbb{R}^\mathbb{N}$ to $\mathbb{R}$. By Cantor Bernstein Theorem, $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$.
Does this proof work or how can I modify/improve it?

A: Maybe, for the first direction you want to express the following, given $r\in\mathbb{R},$ this have the form $a_0,a_1a_2\dots$ where every $a_i$ is a digit, then we can define $f(r)=(a_0,a_1,\dots,a_n,\dots)$
the second part is o.k


text:
Q: Calling the media streaming in a different thread or not for prepareAsync() I am streaming audio from my server. I went through the documentation of prepareAsync() here and this answer from stackoverflow says that it is done on a different thread than the calling UI thread.
So my question is do I need to call the task of audio streaming on a new thread as a good practice or should we continue on the same thread since prepareAsync() is done on a new thread itself.
For reference purpose I am adding my code where I have not created a new thread for calling MediaPlayer class :
Calling Class
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String url = "http://arqamahmad.com/music_app/bensound-cute.mp3";
                    if(Player.player == null){
                        new Player();
                    }
                    Player.player.playStream(url);
                }
            });

Player Class
public class Player {

  MediaPlayer mediaPlayer = new MediaPlayer();
    public static Player player;
    String url = "";

    public Player(){
        this.player = this;
    }

    public void playStream (String url){
        if(mediaPlayer != null){
            try{
                mediaPlayer.stop();
            }catch (Exception e){

            }
            mediaPlayer = null;
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();// Starting only when it is prepared
                }
            });
            mediaPlayer.prepareAsync();//Doing in the background thread
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();
    }

}

A: You can go ahead and call prepareAsync() in the same thread. When the media player is done preparing (often buffering), it notifies the app onPreparedListener() through a different thread (native thread).


text:
Q: Magento module onboarding I am creating a custom Magento 2 module. In Wordpress/Shopify, when installing plugin/extension it shows the onboarding form where the merchant can fill in all the information used by the plugin to run. For example, my module needs to know the merchant's name, address, etc...
However, when installing a new module in Magento 2, I see no onboarding. And I don't know how to do it in Magento 2. The merchant can't use my module if they don't answer some questions :)
Could you show me how to do that in Magento 2?

A: If I understand right what you need is to make the merchant insert the values on a form and don't have a default value right?
I don't think you can do that, might be wrong tho, but the best solution I can think of is to have some default values, have some condition that whatever the module doesn't work and show a warning if the values are the default ones, and create a tab in admin so the merchant can insert the info you need btw it might help, you can get some on the information the is already in the system like store address, store name, etc etc...
Sorry if I understood it incorrectly :D
EDIT:
Something like this
And if the "Page Title" is "Some value" block the "Module Enable" dropdown, that way you force the merchant to change that field to something else, do it for all the fields needed


text: Q: How to assign the selected data to a specific graph. ( VBA script ) Am trying to auto select the source data for a chart using vba script. The script is designed to include the newly added column as a source data to the graph. But there are multiple graphs in the same sheet that has to be updated,


text:
Q: Place TextView at right of other one and make it always visible It is easy to place one TextView at right of another TextView but when width on base TextView more than screen size right TextView became not visible.
My XML layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/messages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:lines="1"
    android:text="Messages" />

<TextView
    android:id="@+id/counter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:background="@drawable/bg_white_r30p0pl10"
    android:drawableRight="@drawable/arrow_orange"
    android:text="800" />

</LinearLayout>

How to make right TextView screen even if base TextView width is huge?
UPD:
In other words I need:
If first TextView is short:
   |[ShotrTextView][TextView]      |

If first TextView is long:
   |[LooooooongTextVi...][TextView]|

A: The solution is TableLayout usage with shrinkColumns = 0
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0" >

<TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/messages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:lines="1"
        android:text="Messages" />

    <TextView
        android:id="@+id/counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:background="@drawable/bg_white_r30p0pl10"
        android:drawableRight="@drawable/arrow_orange"
        android:text="800" />

</TableRow>

</TableLayout>

A: Try this
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ellipsize="end"
        android:inputType="text"
        android:text="" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="0"
        android:inputType="text"
        android:text="12345" />

</LinearLayout>

A: Posting this as thinking line the only way to do the so...
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:singleLine="true"
                android:layout_height="wrap_content"
                android:text="Medium TextMedium TextMedium TextMedium Text"
                android:maxWidth="280dp"
                android:ellipsize="end"
                />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="HHH"
                 />

And create one dimension file like this and use it.

A: Check the answer in: Two TextViews side by side, only one to ellipsize?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TextView android:id="@+id/messages" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"
android:ellipsize="end" android:lines="1" android:text="Message" />
<TextView android:id="@+id/counter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp"
  android:layout_weight="1" android:background="@drawable/bg_white_r30p0pl10" android:drawableRight="@drawable/arrow_orange" android:text="800" />

</LinearLayout>


text:
Q: openjdk8 for Android 7.1.2 version When I compiled the andriod 7.1.2. I encountered this problem. I had checked my openjdk version. It is openjdk8. So, what is another possibility?
ninja: error: 'out/host/linux-x86/obj32/SHARED_LIBRARIES/libopenjdkjvm_intermediates/export_includes', needed by 'out/host/linux-x86/obj32/SHARED_LIBRARIES/libopenjdk_intermediates/import_includes', missing and no known rule to make it

One solution is from here:
https://groups.google.com/forum/#!topic/android-building/Gz3joT38lVk
Do disable ninja to compile. However, it also has this problem.
So, what is the solution for this?

A: Finally I solved my problem with deleting and downloading the AOSP again. I suppose that the problem is caused by the multiple and various android version downloading.


text:
Q: find the string and number values corresponding keys I have a column and data array. Trying to map over the column and based on the type of the data, trying to take only string and number, and other values will be discarded.
In the data column -> ID is a number and Starttable is a string, I want to keep only those.
trying to get the result like
[{fieldname: "ID"}, {fieldName: "startTable"}]

const searchColumnUpdate = (columns, data) =>
  columns.map((x, i) => {
    let columnName =
      typeof x.accessor === "string" ? x.accessor : x?.id || x?.Header;
    if (typeof data[columnName] === "string" || "number") {
      return {
        fieldName: columnName
      };
    }
    return false;
  });

const columns = [
  { Header: "ID", id: "Id", accessor: "ID", sortType: "number" },
  { id: "startTable", Header: "Starttable", sortType: "alphanumeric" },
  { id: "targetTable", Header: "Targettable", sortType: "alphanumeric" },
  { Header: "Joinpath", id: "joinPath", useOnJoinsPage: true, width: 120 }
];
const data = [
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 1,
    Child: null,
    Starttable: "1",
    Targettable: true,
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "3",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "4",
    joinPath: true
  }
];

console.log(searchColumnUpdate(columns, data));

A: After fixing some minor typos in your sel array (spelling of "fieldname" and "Starttable") the following one-liner should do the trick:
const res=data.map(el=>Object.fromEntries(sel.map(({fieldname})=>[fieldname,el[fieldname]])));

Here the whole thing as a snippet:

const columns = [
  { id: "Id", Header: "ID", accessor: "ID", sortType: "number" },
  { id: "startTable", Header: "Starttable", sortType: "alphanumeric" },
  { id: "targetTable", Header: "Targettable", sortType: "alphanumeric" },
  { Header: "Joinpath", id: "joinPath", useOnJoinsPage: true, width: 120 }
],
  sel = [{fieldname: "ID"}, {fieldname: "Starttable"}],
  data = [
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 1,
    Child: null,
    Starttable: "1",
    Targettable: true,
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "3",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "4",
    joinPath: true
  }
];

const res=data.map(el=>Object.fromEntries(sel.map(({fieldname})=>[fieldname,el[fieldname]])));

console.log(res)

UPDATE
It seems I misunderstood your question. As you really want the array sel to be the output - and it should - according to your requirements look like:
sel = [{fieldname: "ID"}, {fieldname: "Starttable"}, {fieldname: "Guid"}]

because Guid is also of type "string" - then you can do it like shown below:

const data = [
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 1,
    Child: null,
    Starttable: "1",
    Targettable: true,
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "2",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "3",
    joinPath: true
  },
  {
    Guid: "0280cf7a-af6a-40af-9bc4-73c14c8f4fa7",
    ID: 2,
    Child: null,
    Targettable: true,
    Starttable: "4",
    joinPath: true
  }
];

const res=Object.keys(data.reduce((a,c)=>{
 Object.entries(c).forEach(([k,v])=>{
  if(["number","string"].includes(typeof v)) a[k]=1;
 });
 return a;
}, {})).map(k=>({fieldname:k}))
console.log(res)


text:
Q: Camel bindy marshal to file creates multiple header row I have the following camel route:
from(inputDirectory)
  .unmarshal(jaxb)
  .process(jaxb2CSVDataProcessor)
  .split(body()) //because there is a list of CSVRecords
  .marshal(bindyCsvDataFormat)
  .to(outputDirectory); //appending to existing file using "?autoCreate=true&fileExist=Append"

for my CSV model class I am using annotations:
@CsvRecord(separator = ",", generateHeaderColumns = true)
...

and for properties
@DataField(pos = 0)
...

My problem is that the headers are appended every time a new csv record is appended.
Is there a non-dirty way to control this? Am I missing anything here?

A: I made a work around which is working quite nicely, creating the header by querying the columnames of the @DataField annotation. This is happening once the first time the file is written. I wrote down the whole solution here:
How to generate a Flat file with header and footer using Camel Bindy

A: I ended up adding a processor that checks if the csv file exists just before the "to" clause. In there I do a manipulation of the byte array and remove the headers.

A: Hope this helps anyone else. I needed to do something similar where after my first split message I wanted to supress the header output. Here is a complete class (the 'FieldUtils' is part of the apache commons lib)
package com.routes;

import java.io.OutputStream;

import org.apache.camel.Exchange;
import org.apache.camel.dataformat.bindy.BindyAbstractFactory;
import org.apache.camel.dataformat.bindy.BindyCsvFactory;
import org.apache.camel.dataformat.bindy.BindyFactory;
import org.apache.camel.dataformat.bindy.FormatFactory;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.commons.lang3.reflect.FieldUtils;

public class StreamingBindyCsvDataFormat extends BindyCsvDataFormat {

    public StreamingBindyCsvDataFormat(Class<?> type) {
        super(type);
    }

    @Override
    public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
        final StreamingBindyModelFactory factory = (StreamingBindyModelFactory) super.getFactory();
        final int splitIndex = exchange.getProperty(Exchange.SPLIT_INDEX, -1, int.class);
        final boolean splitComplete = exchange.getProperty(Exchange.SPLIT_COMPLETE, false, boolean.class);

        super.marshal(exchange, body, outputStream);

        if (splitIndex == 0) {
        factory.setGenerateHeaderColumnNames(false); // turn off header generate after first exchange
        } else if(splitComplete) {
        factory.setGenerateHeaderColumnNames(true); // turn on header generate when split complete
        }
    }

    @Override
    protected BindyAbstractFactory createModelFactory(FormatFactory formatFactory) throws Exception {
        BindyCsvFactory bindyCsvFactory = new StreamingBindyModelFactory(getClassType());
        bindyCsvFactory.setFormatFactory(formatFactory);
        return bindyCsvFactory;
    }

    public class StreamingBindyModelFactory extends BindyCsvFactory implements BindyFactory {

        public StreamingBindyModelFactory(Class<?> type) throws Exception {
            super(type);
        }

        public void setGenerateHeaderColumnNames(boolean generateHeaderColumnNames) throws IllegalAccessException {
            FieldUtils.writeField(this, "generateHeaderColumnNames", generateHeaderColumnNames, true);
        }

    }

}


text:
Q: C# launch a program with mandatory parameters and optional parameters from cmd I need to call a program from cmd using an array of numbers(mandatory) and an int time(optional). I have never done this so i'm a bit shaky on the details.
The path is D:\Robert\FactorialConsoleApplication\FactorialConsoleApplication\bin\Debug\FactorialConsoleApplication.exe
As you can tell, the program calculates the factorial of the numbers in the array. The int time is used as a delay in order to display the progress of the stack.
How do I call the program with parameters?
Thanks in advance!
P.S. Here is some of the code
class Program
{
    public static void Progress(ProgressEventArgs e)
    {
        int result = e.getPartialResult;
        int stack_value = e.getValue ;
        double max = System.Convert.ToDouble(numbers[j]);
        System.Convert.ToDouble(stack_value);
        double percent = (stack_value / max) * 100;

        Console.CursorLeft = 18;
        Console.Write(result + " ");
        Console.CursorLeft = 46;
        Console.Write(System.Convert.ToInt32(percent) + "%      ");

    }
    public static void Calculate(int number, int time=0)
    {

        Factorial Fact = new Factorial();
        Fact.Progression += new Factorial.ProgressEventHandler(Progress);
        Console.Write("\n" + "Partial results : ");
        Console.CursorLeft = 35;
        Console.Write("Progress : ");
        int Result = Fact.CalculateFactorial(number, time);
        Console.WriteLine(" ");
        Console.WriteLine("The factorial of " + number + " is : " + Result);

        Console.ReadLine();
    }

    static int j;
    static int[] numbers;

    public static void Main(string[] args)
    {
        int i=0;
        bool ok = false;
        string line = string.Empty;
        numbers = new int[10];
        Console.Write("Please insert wait time (0,1 or 2) : ");
        int time = int.Parse(Console.ReadLine()) * 1000;
        Console.Write("Please insert a number : ");
        do
        {
            line = Console.ReadLine();
            if (line != "")
            {
                i++;
                numbers[i] = int.Parse(line);

            }
            else
            {
                ok = true;
            }
        }
        while (ok == false);
        for (j = 1; j <= i; j++)
        {

            Calculate(numbers[j],time);
        }

    }
}

A: In .net you can use Process.Start from System.Diagnostics to launch an application, you can pass parameters too
For example Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm"); will open Internet Explorer and pass the value "C:\\myPath\\myFile.htm" as parameter to it.For more examplles check the MSDN article on Process.Start method
Update
If in case you are looking to take parameters to your application, when launching itself you don't have to do anything, you are already doing that, the parameter args in your Main method will hold the arguments passed to your application, just try and parse those values in the args array to int array and you are good to go.

A: Ok, so here is the solution.
I used an args parser like this :
static int extra;
    public static void Main(string[] args)
    {

        foreach (string s in args)
        {
            extra = int.Parse(s);

            Calculate(extra);
        }
     }

And I changed :double max = System.Convert.ToDouble(numbers[j]);
to :double max = System.Convert.ToDouble(extra);
To call it I open cmd in the directory where the exe is and I type :
Program.exe 3 4 5
It will calculate the factorials of 3, 4 and 5 respectively


text:
Q: MySQL Error Code: 1205. Lock wait timeout during update with inner join I am trying to update the Time_Stamp field in my table, simple_pack_data, to match the values in the similarly titled field in my temp_data table. The tables each have fields called Test_Number and Time_Marker, which I'm using to INNER JOIN the tables. Time_Marker is like a reading count, where Time_Stamp is an actual time from the start of the test.
I want to update the Time_Stamp one test at a time, so the code I have been trying is:
UPDATE simple_pack_data s
INNER JOIN (
    SELECT *
    FROM temp_data t
    WHERE t.Test = "3"
    ) AS tmp
ON s.Test_Number = tmp.Test_Number AND s.Time_Marker = tmp.Time_Marker
SET s.Time_Stamp = tmp.Time_Stamp
WHERE s.Test_Number = "3";

When I run this it takes over 50 seconds and I get the 1205 error. If I run a similarly structured select statement:
SELECT *
FROM simple_pack_data s
INNER JOIN (
    SELECT *
    FROM temp_data t
    WHERE t.Test = "3"
    ) AS tmp
ON s.Test_Number = tmp.Test AND s.Time_Marker = tmp.Time_Marker
WHERE s.Test_Number = "3";

It takes much less than a second and I know join is working fine. Is the update really taking that long? If so, is there any way to change the timeout value so it can get through it?

A: Try see if your MySQL Server had a process in running.
To see that, run the command on MySQL Client:
SHOW FULL PROCESSLIST;

See id, state and info columns and analyze the problem. After you find the problem, kill the process with:
KILL <PROCESS ID>;

A: This error is entirely MySQL not doing as it should. The best solution is to get off of MySQL, but lacking that ability, this performance blog post has helped me get around this in the past.
MySQL has a lot of these little gotchas. It's like working in Access, half the time the program is going to do the wrong thing and not raise an error.


text:
Q: PHP. Download from FTP with stream or custom ftp wrapper I need help with creation of custom FTP wrapper in PHP.
I used
$h=fopen('ftp://....');

But this doesn't work well with all FTP servers (sometimes problems with active/passive mode) and i can not control this with the wrapper.
I use functions from http://php.net/manual/en/book.ftp.php and all works fine. I have problems only with download with PHP FTP wrapper.
I need to use wrapper because i don't want to store downloaded file to the disk. I read part of a file from a stream and then output to a user browser.
So i want to create custom FTP wrapper in PHP. And best of all if it is based on functions from there http://php.net/manual/en/book.ftp.php .
I see example there http://php.net/manual/en/function.ftp-fget.php
function ftp_get_contents ($conn_id, $filename,
//Create temp handler:
     $tempHandle = fopen('php://temp', 'r+');

//Get file from FTP assuming that it exists:
     ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0));

     //Getting detailed stats to check filesize:
     $fstats = fstat($tempHandle);

     return fread($tempHandle, $fstats['size']);
 }

But this is not good as it saves full file to the disk and only after this i can read from the local file.
DO you know something like this but allows me to read file with portions from FTP server without caching full file locally?
Thanks.

A: I found a solution.
i do
$h=popen('wget -q -O - ftp://.....','r');

it works fine. But wget must be installed.


text:
Q: [MsgId: MERR-27040]: GWT - ERROR [GWT_DFE] - java.lang.reflect.InvocationTargetException in Vugen Script I am getting the following error when running the Vuser Script. The script uses html/HTTP protocol and GWT DFE is enabled. I gave the classpath with all the .jars and .wars. All my request bodys are decoded to xml. I didn't do any parameterization or correlation on this script yet.
Error -27040: Data Format Extension: Extension: GWT - ERROR [GWT_DFE] - java.lang.reflect.InvocationTargetException

<com.XX.dfe.GWT__Request><moduleBaseURL>https://serverIP/platform-ui/</moduleBaseURL><rpcRequest><flags>0</flags><method><class>com.XXXX.product.platform.service.v1.client.gwt.api.PlatformLo
End dump of original buffer.

Action.c(75): Error: C interpreter run time error: Action.c (75):  Error -- memory violation : Exception ACCESS_VIOLATION received.

web_set_max_html_param_len("16384");

Should I do any correlation? Can that be a reason why this script is failing?

A: it's important to see the failing step in order to determinate the root cause of the error.
you can try to verify that the class exist in the provided GWT DFE class path (use JDGUI for example), also check the JRE version (WAR vs the one in LR folder) and also verify that the permutation number in the war file is the same as in the script


text:
Q: After enabling TLSv1.2 in hostapd(an Integrated EAP RADIUS server),"fatal alert:decode error" is received from client(wpa_supplicant) during EAP-TLS I am in a big issue regarding TLSv1.2 and unable to resolve this.
Scenario:

*

*Hostapd should act as an integrated EAP server.I have an openwrt device on which hostapdv2.6-devel is running.
2.Wpa_Supplicant is acting as a client and should talk to hostapd for successful authentication.wpa_supplicantv2.6-devel is running on a different openwrt device.
3.Two way SSL handshake(EAP-TLS) should happen successfully and hostapd should authenticate the client device without any issue.
4.Requirement is that this communication should take place on TLSv1.2 i.e. server (hostapd)is bound to send TLSv1.2.

Configuration:
EAP server(hostapd configuration):
1.Since by default server is sending TLSv1.0 to the client so I made it to send TLSv1.2 forcefully by recompiling the package for TLSv12 and install again on the router.
2.Created a configuration file, which has all the server certificate, ca certificate chain eap_server=1 etc.
3.Started the hostapd process on the device successfully.
client configuration(wpa_supplicant):
1.Created a configuration file, which has all client certificate, CA chain, identity, SSID etc.
2.Started the wpa_supplicant on the device successfully.
SSL transactions:
1.client send client hello message and TLSv1.2 in it.
2.Server responds with server hello message and TLSv1.2
3.Server sends its certificate, serverkeyexchange, certificate request message.
4.Afterward a fatal alert occurs "decode_error" and no more transaction are seen and authentication gets failed.
Please see the wireshark capture below.
ClientHello

ServerHello

Alert Message

Kindly help me to resolve this issue as its making my life difficult.
Please let me know if any other information is required.
Thanks.


text:
Q: get index of selcted item in QListView in python self.listOfSongs = QtWidgets.QListView(self.centralwidget)
self.listOfSongs.setGeometry(QtCore.QRect(80, 160, 191, 192))
self.listOfSongs.setObjectName("listOfSongs")
self.model = QtGui.QStandardItemModel()
self.listOfSongs.setModel(self.model)
self.updateList()

def updateList(self):
   self.model.clear()
   for x in self.table:
      item = QtGui.QStandardItem(x)
      self.model.appendRow(item)

I hope someone can tell me how to get the item or the index of the item that I choose by selecting or click on?
Using lib pyQT5 in python

A: QStandardItemModel is a model so you can use all the methods of QAbstractItemModel. You can iterate over rows and use the item() method to get the QStandarItem associated with each index, and then use the text() method of the QStandarItem to get the text.
    self.listOfSongs = QtWidgets.QListView(self.centralwidget)
    self.listOfSongs.setGeometry(QtCore.QRect(80, 160, 191, 192))
    self.listOfSongs.setObjectName("listOfSongs")
    self.model = QtGui.QStandardItemModel()
    self.listOfSongs.setModel(self.model)

    for text in ["Item1", "Item2", "Item3", "Item4"]:
        it = QtGui.QStandardItem(text)
        self.model.appendRow(it)

    self.listOfSongs.clicked[QtCore.QModelIndex].connect(self.on_clicked)

def on_clicked(self, index):
    item = self.model.itemFromIndex(index)
    print (item.text())

on click:


text:
Q: for each link change color based on array I have an array containing the hrefs of colours and I want to go though each link in my nav and apply a different colour based on the order of the array.
I think this is possible but i'm missing something.
Here is my code
    var colourValue = [ "fff", "000", "FF6600", "FF00FF", "FFFF00" ];
//this is how console displays the array, I have no control over the values.
        var values = [];
        values.push(colourValue);
        console.log(values);

         $.each(values, function(index, value) {
             var colorStyle = "#" + value +"";
             $(".nav li:first-child").find("a").css("color",colorStyle);
            });

Don't really know what I'm missing, Any tips?
Thanks very much (colourValue is dynaimcally populated but for this eg I wrote it out).

A: The problems
var colourValue [ "#fff", "#000", "#FF6600", "#FF00FF", "#FFFF00" ]
var values = [];
values.push(colourValue);

That's a very odd bit of code. You define an array (actually, you don't -- it's missing =) and give it some values, then create another array and append each of the values of the first array to the second.  You don't need two arrays here, you can just loop through the origial array.
var colorStyle = "#" + value +"";

That makes ##fff, which is obviously not what you want.  You can just access the value with value.
$(".nav li:first-child").find("a").css("color",colorStyle);

This is the big problem. It loops through all the members of values, and on each iteration sets every link to have the colour of the current member of the array.  Your selection, however, will only ever have the links in the first li element, which is clearly not what you want.  You need .nav li a.
The solution
jQuery has lots of nice ways of working with selections.  You probably want something like this:
var colourValue = [ "#fff", "#000", "#FF6600", "#FF00FF", "#FFFF00" ]
$('.nav li a').css('color', function(idx) {
    return colourValue[idx % colourValue.length];
});

This runs a function for each element in the selection. The function receives the element's position (0-indexed) in the selection as its first argument (idx).  Using the modulus operator (%) in this way says "return 0 for the first item, 1 for the second ... 4 for the fifth, 0 for the sixth, etc".  You then use this value to find the correct colour from the array.
The return value of the function is set as the value of the CSS property.

A quick note to this: if you have the same number of links to be coloured as you do colours, the modulus operation is unnecessary. You could just use return colourValue[idx];.

A: Try this:
var yourArray = ["#fff", "#000", "#FF6600", "#FF00FF", "#FFFF00"];
$('.nav a').each(function(i) {
    $(this).css("color", yourArray[i]);
});

You can really cut down the code this way, you don't need the $.each. Also, doing a selector the way you were is not only going to return the wrong results, but will also give you terrible performance. You were traversing the dom every time you walked through an array item. Its better to get your links first, then apply the array items to them, not the other way around.

A: For one you are missing the "=" on var colourValue = [...
The other problem is that you are assigning the "#" to the color hex twice.
This should work:
var colourValues = ["#fff", "#000", "#FF6600", "#FF00FF", "#FFFF00"];

$.each(colourValues, function(index, colorStyle){
   $(".nav li:first-child").find("a").css("color", colorStyle);
});

A: var colourValues = ["#fff", "#000", "#FF6600", "#FF00FF", "#FFFF00"];

$.each(colourValues, function(index, value){
   $(".nav li:first-child a").eq(index).css("color", value);
});


text:
Q: Should I be using an object for this JS/PHP interaction? Does this look right? Part of a site I am building uses a javascript ajax request to hit a PHP script that retrieves, parses, sorts and paginates and returns results from an XML file. I have done this in a pretty straight forward fashion on the PHP side with variables POST variables being retrieved, sanitized and reassigned, SimpleXML loading the file and using an xpath query to grab the needed bits, sorting handled by the SPL's LimitIterator, etc.
What I am wondering is if this should be wrapped up in an object and, perhaps most importantly, how this object should be constructed.
The code is used, with fairly minor changes (like the sorting direction, the specific xpath query and the particular XML file) for a number of different requests in different parts of the site so I suspect that perhaps turning it into a reusable object might be the way to go? What do you think? Should I watch out for anything? Any special way this should be approached (like, does it need to be a Singleton or can I pass the POST variables into a constructor and then have that separate them out into their various reassigned variables)? Basically I am wondering if I am on the right path with doing this in an object oriented manner and I was thinking something like this (this is meant to be a pseudo code sort of example and my use of some things is off, I know. Please make suggestions for improvement like am I using $this->foo properly or am I using public/private properly?):
        class GetXMLData() {
            public $start;
            public $end;
            public $xmlfile;
            public $limited;
            private $results;

            public function __constructor($_POST, $xmlfile) {
            $this->start = sanitize($_POST['start']);
            $this->end = sanitize($_POST['end']);
            $this->xmlfile = $xmlfile;
            }

            //load the xml file
            private function loadFile($this->file) {
                return simplexml_load_file($this->file);
            }

            private function sorting(){
                // an internal sorting function that could use loadFile() perhaps and then return $results to the pagination function?
            }

            private function paginate($this->results) {
                $this->limited = new LimitIterator(new ArrayIterator($this->results), $start, $end);
                return $this->limited
            }

        }

    $stuff = new GetXMLData($_POST, $xmlfile);
    return $stuff;

A: Objects have nothing to do with POST, or interacting with JavaScript, or any of that. They are simply a way of organizing code on the server.

A: It looks fine to me, but I definitely would not make it a singleton.
This seems to be a common misconception with the singleton pattern: it's not for use when you think you will only need one of an object, it's for when have multiples of that object would cause problems, and you need to guarantee there is over only one instance of it.
also, I would probably make all of the variables private, and use getters and setters for whenever you need access to them (if you need access to them).


text:
Q: Check a string for banned words I have some code that creates a string 6 characters long of random alphanumerics ("a key").
ex: "AJ4L3I"
I want to make sure these keys never contain terms that I can add to an array.
NSArray *bannedTerms = @[@"666", @"ass", @"hell", //etc., nil];
How can I check if an NSString like "HJ666P" contains a term in my bannedTerms NSArray or NSMutableArray.
Thanks :)

A: You can call rangeOfString: in a loop to see if you get a match, or use a regex to check for all words at once, without a loop:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
    regularExpressionWithPattern:@"666|ass|hell|...etc."
                         options:NSRegularExpressionCaseInsensitive
                           error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:passcode options:0 range:NSMakeRange(0, passcode.length)];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
    // Found a banned word.
}

A: NSString *string = // generate the string
for(NSString *bannedTerm in bannedTerms) {
     NSRange range = [string rangeOfString:bannedTerm options:NSCaseInsensitiveSearch];
     if(range.location != NSNotFound) {
          return NO; // failed check
     }
}
return YES; // passed check


text:
Q: Subtract on Pandas DF
I wanted to subtract all CR with DR row for each account no separately.
Expected output :
account_no |   REMIT
10051056346  |   7,04,215
10051059074  |   9,39,395

A: You can use the xs selector:
out = (df
 .xs('CR', level='type')
 .sub(df.xs('DR', level='type'))
)


text:
Q: Enable https on GitLab CE with Letsencrypt with Apache2 running on Ubuntu 14.04 As in the title:
How can I enable https on GitLab CE (9.1.4) with lets-encrypt and Apache2 running on Ubuntu 14.04?
Some Background:
HTTPS works for my domain. E.g. www.example.com is establishing a secure connection via https. Safari says

Issued by: Let's Encrypt Authority X3
Expires: Tuesday, 8. August 2017 at 16:12:00 Central European Summer Time

I'm configured Gitlab CE as followed first with http in /etc/gitlab/gitlab.rb:
external_url 'http://gitlab.example.com:1337'

This works fine, but my goal is to use the power of lets-encrypt to secure my connection to my gitlab instance.
I followed many tutorials changing my /etc/gitlab/gitlab.rb as folling:
external_url 'https://gitlab.example.com:1337'

nginx['redirect_http_to_https'] = true
nginx['ssl_certificate'] = "/etc/gitlab/ssl/example.com.crt"
nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/example.com.key"

Also I added just for testing if it works to /etc/gitlab/gitlab.rb:
gitlab_rails['gitlab_https'] = true
gitlab_rails['gitlab_port'] = 1337

But nothing worked! What I'm doing wrong?
Additional info:
I copied from /etc/letsencrypt/live/example.com/fullchain.pem to /etc/gitlab/ssl/example.com.crt
and
I copied from /etc/letsencrypt/live/example.com/privkey.pem to /etc/gitlab/ssl/example.com.key
I'm using apache2 as my "front" server, and the nginx instance is the built-in nginx shipped with GitLabe CE


text:
Q: Changing CSS with html onClick window.print()? I have a web page that has CSS settings to put a 15% margin around the page so it looks better for the user. I have a button that allows them to print the page, but the same margin is applied. The button has a setting to be hidden when printing, and I'm wondering if there is a way to remove the margins or change the margins for printing when they click the button. The code I have for the button right now is:

body {
 margin-left: 20%;
 margin-right: 20%;
}
<button
  id="printButton"
  name="printButton"
  class="btn btn-primary hidden-print"
  onClick="window.print()"
  type="button">
  Print for My Records
</button>

I'd like that change the margins to something like 1% or 2% when the window.print() page comes up.

A: Don't make it difficult! Just use the media query @media print in your stylesheet.

body {
 margin-left: 20%;
 margin-right: 20%;
}

@media print and (min-width: 480px) {
  body {
    margin-left: 0;
    margin-right: 0;
  }

  #printButton {
    display: none;
  }
}
<button
  id="printButton"
  name="printButton"
  class="btn btn-primary hidden-print"
  onClick="window.print()"
  type="button">
  Print for My Records
</button>

A: You don't have to alter the margins defined upon button click for the print layout. Just use the @page at-rule to modify the margin properties when the page is being printed.
@page {
  margin: 1cm;
}

body {
  margin-left: 20%;
  margin-right: 20%;
}

Read more here
As this might have compatibility issues with Safari, you can also use the print media-query:
body {
  margin-left: 20%;
  margin-right: 20%;
}

@media print {
  body {
    margin: 1%;
  }
}


text:
Q: AWS AMPLIFY: How to specify auth for custom lambda resolvers How to specify all Cognito users can access custom lambda resolver
type Query {
   tasks: [Task] @function(name: "lambda1-${env}")
   getTask(id:ID!): Task @function(name: "lambda1-${env}")
}

type Task {
  id: ID!
  name: String!
}

I am getting unauthorized when doing
    const taskList = await API.graphql({
      query: tasks,
      authMode: 'AMAZON_COGNITO_USER_POOLS'
    });

A: Finally got it working.
type Query {
   tasks: [Task] @function(name: "lambda1-${env}") @auth(rules: [{ allow: private, provider: userPools }])
   getTask(id:ID!): Task @function(name: "lambda1-${env}")
}

type Task {
  id: ID! @auth(rules: [{ allow: private, provider: userPools }])
  name: String! @auth(rules: [{ allow: private, provider: userPools }])
}

const taskList = await API.graphql({
  query: tasks,
  authMode: 'AMAZON_COGNITO_USER_POOLS'
});


text:
Q: How to insert a max value plus one in mysql in opencart I have the following:
Model File
$max = $this->db->query("SELECT MAX( sort ) FROM lc_menu");
print_r($max);

Printed Values
stdClass Object ( [num_rows] => 1 [row] => Array ( [MAX( sort )] => 64 )
[rows] => Array ( [0] => Array ( [MAX( sort )] => 64 ) ) )

How can I insert max+1 in MySQL query?

A: You can use subquery:
$this->db->query('INSERT INTO ' . DB_PREFIX . ' menu SET
menuname = "$this->db->escape($data['menuname'])",
start_date = "$this->db->escape($data['start_date'])",
start_time = "$this->db->escape($data['start_time'])",
end_date = "$this->db->escape($data['end_date'])",
end_time = "$this->db->escape($data['end_time'])",
link_value = "$this->db->escape($data['link_value'])",
link = "$this->db->escape($alpha['link'])",
sort = ((SELECT MAX(sort) FROM lc_menu) + 1)');


text:
Q: Remote Desktop - Does leaving a session open slow down the server? Like many other development teams, we don't do a good job of signing out after an RDP session. I am trying to convince the team that it's important to use the "Sign Out" feature to close the session. It's my understanding that "Disconnect" or clicking the [X] leaves a session open...
Is the performance of a windows server affected by leaving sessions open? What other issues could arise from this?

A: Will it slow the server down? Possibly. A disconnected session still consumes resources.
The larger implication is the potential security ramifications of leaving an unattended session running on the server. For that reason alone I would strongly encourage the practice of logging out of the session.


text:
Q: how to hide id from url in Laravel 6? hide id from url
https://wallpaperaccess.in/photo/162/download-wallpaper

i want url like this
https://wallpaperaccess.in/photo/download-wallpaper

ImagesController.php
public function show($id, $slug = null ) {

        $response = Images::findOrFail($id);

        $uri = $this->request->path();

        if( str_slug( $response->title ) == '' ) {

                $slugUrl  = '';
            } else {
                $slugUrl  = '/'.str_slug( $response->title );
            }

            $url_image = 'photo/'.$response->id.$slugUrl;

            //<<<-- * Redirect the user real page * -->>>
            $uriImage     =  $this->request->path();
            $uriCanonical = $url_image;

            if( $uriImage != $uriCanonical ) {
                return redirect($uriCanonical);
            }

Route
// Photo Details
Route::get('photo/{id}/{slug?}','ImagesController@show');

NOTE: i don't have any slug column in database, so can we use title as slug?

A: You should add a column field slug and auto-generate it from title
use Illuminate\Support\Str;

$slug = Str::slug($request->input('title'), '-');

In Models\Image.php
public function getRouteKeyName()
{
    return 'slug';
}

In routes\web.php
Route::get('photo/{image:slug}','ImagesController@show');

In app\Http\Controllers\ImagesController.php
use app\Models\Image.php;

...
public function show(Image $image)
{
    // controller will automatically find $image with slug in url
    // $image_id = $image->id;
    return view('your.view', ['image' => $image]);
}

A: In order to use a slug in the URL instead of an id, you'll need to...

*

*Create a column in your table where you store the slug. A good way to make a slug unique is to append the actual id at the end. If you really don't want to see the id anywhere, you have no choice, you'll have to ensure the slug is unique yourself (there are a lot of ways to achieve this).

This is one way to automatically create an unique slug:
Make sure the slug column is nullable, then open your model and add these methods.
They are called "model events".

*

*created is called when the model is, well, created.

*updating is called when you are updating the model but before it's actually updated.

Using created and updating should automatically create the slug when you create or update a Images instance.
    protected static function booted()
    {
        parent::booted();

        static::created(function (Images $images) {
            $images->slug = Str::slug($images->title.'-'.$images->id);
            $images->save();
        });

        static::updating(function (Images $images) {
            $images->slug = Str::slug($images->title.'-'.$images->id);
        });
    }

From a SEO point of view, updating the slug when the title change is arguably not a good practice, so you might want to omit this part (static::updating...), it's up to you.

*Go to your model and add the following method:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug'; //or whatever you call the slug column
}

This way, the router will resolve your model by the slug, not the id.

*In your route file, remove the id and change the name of the slug to match the name of your model:

Route::get('photo/{images}','ImagesController@show'); //here I'm assuming your model is Images from what I see in your controller

*In your controller, change the declaration of your show method to this:

public function show(Images $images)
{
   dd($images);

// if you did all this correctly, $images should be the Images corresponding to the slug in the url.
// if you did something wrong, $images will be an empty Images instance
//
//
// your code...
}

Images should be renamed to Image, models should not be plural. However, it should not make any difference here.


text:
Q: Carthage - How to import FBSDKCoreKit, FBSDKLoginKit, FBSDKShareKit and Bolts with Carthage? The integration via cocoapods is documented and easy, but how can i achieve the same with Carthage?

A: Now it works with Swift.
Catfile:
github "facebook/Facebook-SDK-Swift"

A: Currently it is impossible because Bolts is a static library that will fail to build with Carthage (they only work with dynamic libraries). I've recently added a pull request to Bolts, but who knows how long it will take to move into the Facebook API. Bolts and Carthage


text:
Q: How to create the following function of polynomial? I would like to create a function with an argument 'n' like the following:
(a_n)*x^n + (a_n-1)*x^(n-1) + ... + (a_1)*x+(a_0)
with (a_i)s coefficients known already.
I know it is a simple question but I just can't figure out how to do it.
My thought is to construct a vector of functions:
xx <- numeric(n+1)
  for (i in 1:n+1) {
    xx[i] <- function(x) x^i
  }

and with coe is the vector of coefficient I defined, I could try:
coe %*% xx

which gives me the answer. But this didn't work and R displayed the following error message:
Error in xx[i] <- function(x) { :
  incompatible types (from closure to double) in subassignment type fix

Hope there're some other simpler ways to do this!

A: Function to calculate (a_n)*x^n + (a_n-1)*x^(n-1) + ... + (a_1)*x+(a_0)
p <- function(x,coefs) {
ens <- rev(seq_len(length(coefs)))-1
sapply(x,FUN=function(x)sum(coefs*x^ens))
}

Example
> p(x=2,coefs=c(0.5,-3,1,-2))
[1] -8
> p(x=1:3,coefs=c(0.5,-3,1,-2))
[1]  -3.5  -8.0 -12.5


text:
Q: How to build multiple configurations? I want to build the SLN from command line. I have tried
D:\>msbuild MySolution.sln

Problem is that it fails to build project C which is targeted for x86, while projects A and B are built right. It gives error:

Project "D:.....\MySolution.sln" (1) is building
  "D:.....\MySolution\ToolC\C.csproj" (4) on node 0 (default
  targets).C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(539,9):
  error : The OutputPath property is not set for this project.  Please
  check to make sure that you have specified a valid
  Configuration/Platform combination.  Configuration='Debug'
  Platform='AnyCPU'Done Building Project
  "D:.....\MySolution\ToolC\C.csproj" (default targets) -- FAILED.

Why is it building C for target "Any CPU"?
Details
I have 1 SLN file with 3 C# projects, say, A, B, C.
Projects A and B are default targeted for "Any CPU". Project C is targeted for "x86"
Here is the content of SLN file (only Global section):
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Debug|x86 = Debug|x86
        Release|Any CPU = Release|Any CPU
        Release|x86 = Release|x86
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|x86.ActiveCfg = Debug|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Release|Any CPU.Build.0 = Release|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Release|x86.ActiveCfg = Release|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|x86.ActiveCfg = Debug|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Release|Any CPU.Build.0 = Release|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Release|x86.ActiveCfg = Release|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|x86.ActiveCfg = Debug|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|x86.Build.0 = Debug|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|Any CPU.Build.0 = Release|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|x86.ActiveCfg = Release|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|x86.Build.0 = Release|x86
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal

And, here is the CSPROJ file content for project C:
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    ....
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <OutputPath>bin\x86\Debug\</OutputPath>
    <PlatformTarget>x86</PlatformTarget>
    ....
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <OutputPath>bin\x86\Release\</OutputPath>
    <PlatformTarget>x86</PlatformTarget>
    ....
  </PropertyGroup>

I also tried this, but the problem remains same:
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>

A: Your default configuration of C project is anycpu|debug but there isn't a propertygroup section for that config in what you've show or default values, therefore no Outputpath property exists. Fix that, either add some defaults or a new property group.
Then make sure you've got the right configuration setup in Build->Configuration Manager in VS.
Its hard to know what actual targets you want to build under what configuration in your sln but this sln works for me with standard csprojs (console):
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Debug|x86 = Debug|x86
        Release|Any CPU = Release|Any CPU
        Release|x86 = Release|x86
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|x86.ActiveCfg = Debug|x86
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Debug|x86.Build.0 = Debug|x86
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Release|Any CPU.ActiveCfg = Release|x86
        {AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}.Release|x86.ActiveCfg = Release|x86
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|x86.ActiveCfg = Debug|x86
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Debug|x86.Build.0 = Debug|x86
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Release|Any CPU.ActiveCfg = Release|x86
        {BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}.Release|x86.ActiveCfg = Release|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|x86.ActiveCfg = Debug|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Debug|x86.Build.0 = Debug|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|Any CPU.ActiveCfg = Release|x86
        {CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC}.Release|x86.ActiveCfg = Release|x86
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal

I had to add targets for "Any CPU" to the csproj thru configuration manager, i can give you those to if that helps.
This builds fine using either:
msbuild Your.sln /t:Rebuild /p:Platform="Any CPU"

or
msbuild ConsoleApplication1.sln /t:Rebuild /p:Platform=x86

If you wanted to build both platforms..
You could add a target to your csproj like:
<Target Name="AllPlatforms" Outputs="$(TargetPath)">
    <ItemGroup>
      <AllPlatforms Include="AnyCPU,x86"/>
    </ItemGroup>

    <Message Text="Building All platform %(AllPlatforms.Identity)"/>
    <MSBuild Projects="$(MSBuildProjectFullPath)" Properties="Platform=%(AllPlatforms.Identity)"/>

  </Target>

But it think youd have to call msbuild on your cspoj rather than sln. So you might as well
call it twice using an external script. Its all a bit hacky. Besides you need to alter the output paths for each platform to get the output.


text:
Q: NumberFormatException when trying to use parseInt()and trim() does not fix it Hi I am trying to solve a Kata(coding practice exercise) in CodeWars which is called "Your order, please" (there is a BIG chance that my code won't solve it but I am really just trying to get rid of the error..and there's a link to the exercise at the end in case you want to check it out)
Either way what the Kata basically says is that you will be given a String such as
"4of Fo1r pe6ople g3ood th5e the2"

and you have to order the words by getting the int and returning in the correct order so
"Fo1r the2 g3ood 4of th5e pe6ople"

Now what I coded is supposed to go through each element and get the number to then order it, so I tried to use parseInt and it did not work. I read on another article that trim() would get rid of...
java.lang.NumberFormatException: For input string: "4of" //trim did not fix it

I am not sure whether I did not implement trim() correctly or parseInt() or what is wrong, any help would be very much appreciated and thank you for taking your time to read this. Without further ado here's the code.
public class Kata {
public static String order(String words) {
    String[] unordered = words.split(" ");
    String[] order = new String[unordered.length];
    System.out.println(unordered.length);

    for(int i = 0; i < unordered.length; i++){
        int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;
        order[correctIndex] = unordered[i];
        System.out.println(unordered[i]);
    }

    return "I will return order concatenated";
  }

  public static void main(String[] args) {
      System.out.println(order("4of Fo1r pe6ople g3ood th5e the2"));
  }

}
And the error... (6 is the output before it)
6
Exception in thread "main" java.lang.NumberFormatException: For input string: "4of"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at Kata.order(Kata.java:8)
    at Kata.main(Kata.java:17)

https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/java
(the link to the Kata)

A: Just remove all non-numeric characters (by using regex replacement) and then parse the resulting value to an integer.
for (int i = 0; i < unordered.length; i++){
    String wordNum = unordered[i].trim().replaceAll("\\D+", "");
    int correctIndex = (Integer.parseInt(wordNum)) - 1;
    order[correctIndex] = unordered[i];
}

A: 4of is not an integer string and therefore, you can not parse it into an int. You can replace its non-digit characters (\D) with "" and then you can parse it to an int. Learn more about regex patterns from the documentation of java.util.regex.Pattern.
The problem can be solved in the following simple steps:

*

*Split the sentence on space (which you have already done).

*Create an int[] original and populate it with embedded numeric values from the resulting, String[] unordered.

*Create a clone of original[] and sort the same. Let's say this clone is int[] order.

*Populate a String[] ordered based on order[].

*Join the elements of ordered[] on space.

Demo:
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String words = "4of Fo1r pe6ople g3ood th5e the2";
        String[] unordered = words.split(" ");
        String[] ordered = new String[unordered.length];
        int[] original = new int[unordered.length];

        // Populate order with embedded numeric values
        for (int i = 0; i < unordered.length; i++) {
            original[i] = Integer.parseInt(unordered[i].replaceAll("\\D", ""));
        }

        // Create a clone of original[] and sort it
        int[] order = original.clone();
        Arrays.sort(order);

        // Populate ordered[] based on order[]
        for (int i = 0; i < order.length; i++) {
            for (int j = 0; j < original.length; j++) {
                if (order[i] == original[j]) {
                    ordered[i] = unordered[j];
                    break;
                }
            }
        }

        // Join the elements of ordered[] on space
        String result = String.join(" ", ordered);

        System.out.println(result);
    }
}

Output:
Fo1r the2 g3ood 4of th5e pe6ople

A: NumberFormatException is thrown when

*

*The input string provided might be null. Example-
 Integer.parseInt(null);

*The input string might be empty. Example-
 Integer.parseInt("");

*The input string might be having trailing space. Example-
 Integer.parseInt("123 ");

*The input string might be having a leading space. Example-
 Integer.parseInt(" 123");

The input string may be alphanumeric.Example-
    Long.parseLong("b2");

There are other reasons also. You are trying to pass unordered[i] in parseInt.
int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;

It is an alphanumeric String. So the compiler gives NumberFormatException.
Try using this function to calculate the index instead.
    //Method to find the correctIndex
    static int findIndex(String s)
    {
        char ch;

        //Access all the characters of the String and the find the digit
        for (int i = 0;i < s.length();i++)
        {
            ch = s.charAt(i);

            if (Character.isDigit(ch))
            {
                return ch-49;     //Convert the character to index
            }
        }

        return -1;
     }


text:
Q: Date string conversion from R to CSV in Libre Calc I'm trying to get acquainted with weatherData in R.
Having downloaded a set of temperature data I've then exported it to CSV.
Opening the CSV in Libre Calc shows the date and time for each temperature reading as a string of ten digits. In spite of some Googling I have not found a way of successfully converting the string into the format in which it appears in R.
For example: 1357084200 I believe should translate to 2013-01-01 23:50:00
Any help in getting the correct date in the same date format to appear in Calc via the CSV greatly appreciated.

A: Here is the direct way:
as.POSIXct(1357084200, origin="1970-01-01", tz="GMT")
#[1] "2013-01-01 23:50:00 GMT"

If it's really a character:
as.POSIXct(as.numeric("1357084200"), origin="1970-01-01", tz="GMT")

A: I'm not aware of a direct way of doing this, but I believe I've figured out a workaround.
For starters your example is correct. The long number (timestamp) is the number of seconds passed since 1970-01-01 00:00:00. Knowing this you can actually calculate the exact date and time from the timestamp. It's a bit complicated due to needing to take into account the leap years.
What comes in handy is the ability to supply an arbitrary number of days/months/years to LibreOffice function DATE. So in essence you can find out the number of days represented in timestamp by dividing it by 60*60*24 (number of seconds in a minute, number of minutes in an hour, number of hours in a day). And then supply that number to the date function.
timestamp = 1357084200
days = timestamp / FLOOR(timestamp / (60*60*24); 1) // comes out at 15706
actualdate = DATE(1970; 1; 1 + days) // comes out at 2013-01-01
seconds = timestamp - days * 60 * 60 * 24 // comes out at 85800
actualtime = TIME(0; 0; seconds) // comes out at 23:50:00

Then you can concatenate these or whatever else you want to do.


text:
Q: Display QR Code in e-mail after submit contact form I also have a problem with generating a qr code. I use Contact Form 7 together with Flamingo to generate a QR code. This QR code is generated in the browser, but I don't know how to make it appear in e-mail.
My code:

In 3rd tab i have: %%[_date]-[_serial_number]


text:
Q: Tomcat8 The origin server did not find a current representation for the target resource or is not willing to disclose that one exists my url is http://localhost:8080/guacamole it returns
HTTP Status 404 – Not Found

Type Status Report

Message /guacamole

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/8.5.30 (Ubuntu)

and for url localhost:8080 it shows
It works !

If you're seeing this page via a web browser, it means you've setup Tomcat successfully. Congratulations!

This is the default Tomcat home page. It can be found on the local filesystem at: /var/lib/tomcat8/webapps/ROOT/index.html

Tomcat8 veterans might be pleased to learn that this system instance of Tomcat is installed with CATALINA_HOME in /usr/share/tomcat8 and CATALINA_BASE in /var/lib/tomcat8, following the rules from /usr/share/doc/tomcat8-common/RUNNING.txt.gz.

You might consider installing the following packages, if you haven't already done so:

tomcat8-docs: This package installs a web application that allows to browse the Tomcat 8 documentation locally. Once installed, you can access it by clicking here.

tomcat8-examples: This package installs a web application that allows to access the Tomcat 8 Servlet and JSP examples. Once installed, you can access it by clicking here.

tomcat8-admin: This package installs two web applications that can help managing this Tomcat instance. Once installed, you can access the manager webapp and the host-manager webapp.

NOTE: For security reasons, using the manager webapp is restricted to users with role "manager-gui". The host-manager webapp is restricted to users with role "admin-gui". Users are defined in /etc/tomcat8/tomcat-users.xml.

but i need apache tom server site


text:
Q: Consulta a ORACLE que necesito modificar Soy nuevo trabajando con ORACLE y me las ingenié para realizar una consulta que trae la información que necesito, el problema es que me las trae en filas y necesito que sea en columnas.
Esta es la query:
SELECT COUNT(*) all_inclusives FROM aabb_platform.g_tb_outdoors
WHERE servicio_ratecode LIKE 'ALL%' AND
servicio_fecha BETWEEN TO_DATE('2019-10-12', 'yy-mm-dd') AND TO_DATE('2019-10-12', 'yy-mm-dd')
UNION ALL
SELECT COUNT(*) full_board FROM aabb_platform.g_tb_outdoors
WHERE servicio_ratecode LIKE 'FULL%' AND
servicio_fecha BETWEEN TO_DATE('2019-10-12', 'yy-mm-dd') AND TO_DATE('2019-10-12', 'yy-mm-dd')
UNION ALL
SELECT COUNT(*) b_b FROM aabb_platform.g_tb_outdoors
WHERE servicio_ratecode LIKE '%BB%' AND
servicio_fecha BETWEEN TO_DATE('2019-10-12', 'yy-mm-dd') AND TO_DATE('2019-10-12', 'yy-mm-dd')

Este es el resultado:
ALL_INCLUSIVES
22
0
7

Esto es lo que necesito lograr:
ALL_INCLUSIVES FULL_BOARD B_B
      22           0       7

De antemano muchas gracias.

A: Compañeros,
Encontré la forma de hacerlo y es la siguiente:
SELECT SERVICIO_FECHA,
  COUNT(CASE WHEN SERVICIO_RATECODE LIKE 'ALL%' THEN 1 END) AS ALL_INCLUSIVE,
  COUNT(CASE WHEN SERVICIO_RATECODE LIKE 'FULL%' THEN 1 END) AS FULL_BOARD,
  COUNT(CASE WHEN SERVICIO_RATECODE LIKE '%BB%' THEN 1 END) AS B_B
FROM AABB_PLATFORM.G_TB_OUTDOORS
WHERE SERVICIO_FECHA BETWEEN TO_DATE('2019-10-12', 'yy-mm-dd') AND TO_DATE('2019-10-12', 'yy-mm-dd')
GROUP BY SERVICIO_FECHA


text:
Q: No ejecuta una sentencia con parámetro de sustitución de nombre PDO Buenas, intento ejecutar una sentencia preparada con parámetros de sustitución de nombre por medio de PDO pero esta no muestra nada, por el lado de la base de datos está correcto pues realizándola de otras formas si que lo muestra.
require_once "conexion.php";

$busqueda = "ciudad";
$dato = "Valencia";

try{

$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM pdo WHERE :busqueda = :dato";
$result = $con->prepare($sql);

$result->bindParam(":busqueda",$busqueda, PDO::PARAM_STR);
$result->bindParam(":dato", $dato, PDO::PARAM_STR,12);
$result->execute();

while($row = $result->fetch(PDO::FETCH_ASSOC)){
    echo "id: " . $row["id"] . "
";
    echo "Nombre: " . $row["nombre"] . "
";
    echo "Ciudad: " . $row["ciudad"] . "
";
    echo "Edad: " . $row["edad"] . "
";
    echo "
";
}
$result->closeCursor();

} catch(Exception $e){
die("Erorr: " . $e->getMessage() . "
Fila: " . $e->getLine());
}

Espero que vosotros encontréis rápido mi error. Un saludo y gracias

A: Por lo que parece no puedo usar esto para sustituir los campos, es decir, el campo del where tengo que ponerlo fijo o por medio de una variable, por lo que parece es para sustituir los valores para realizar la consulta, así si funciona.
require_once "conexion.php";

$dato = "Valencia";

try{

$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM pdo WHERE ciudad = :dato";
$result = $con->prepare($sql);

$result->bindParam(":dato", $dato, PDO::PARAM_STR);
$result->execute();

while($row = $result->fetch(PDO::FETCH_ASSOC)){
    echo "id: " . $row["id"] . "
";
    echo "Nombre: " . $row["nombre"] . "
";
    echo "Ciudad: " . $row["ciudad"] . "
";
    echo "Edad: " . $row["edad"] . "
";
    echo "
";
}
$result->closeCursor();

} catch(Exception $e){
die("Erorr: " . $e->getMessage() . "
Fila: " . $e->getLine());
}


text:
Q: Google Api is not giving location I am using google API to get location in my project. It gives location sometimes but most of the time it does not give any location. and   from today it is giving server return an error 403 forbidden.
When i am hitting the URL in my browser it is giving location.
I am not using any key for my API can it cause this issue.
Just to add-
I get the lat and long from my api and then i get the location from google api and stores it in my database.
What i am doing is:-
public static string getGoogleLocationByLogLat(string log, string lat)
{

    try
    {
         if (log == "")
    {
        log = "0.0";
    }
    if (lat == "")
    {
        lat = "0.0";
    }

    XmlTextReader xReader;
    bool element = false;
    string location = "", time, GL, parentEmail, respDateTime;
    string parentElementName = "";
    string childElementName = "";
    string childElementValue = "", prmryCntact = "";

    string url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + lat + "," + log + "&sensor=true";

    xReader = new XmlTextReader(url);

        while (xReader.Read())
        {

            if (xReader.NodeType == XmlNodeType.Element)
            {

                if (element)
                {
                    parentElementName = parentElementName + childElementName + "<br>";
                }

                element = true;

                childElementName = xReader.Name;

            }

            else if (xReader.NodeType == XmlNodeType.Text | xReader.NodeType == XmlNodeType.CDATA)
            {

                element = false;

                childElementValue = xReader.Value;

                if (childElementName == "formatted_address")
                {
                    location = childElementValue;
                    break;
                }
            }

        }

    if (location.Trim() == "")
    {
        location = "Location not found";
    }

    return location;
    }
    catch (Exception ex)
    {
        return "LOCATION NOT FOUND";
    }
}

A: Add your API key
&key=yourkey

With the latest policy updates to the maps api, i believe this must be the case that you're hitting...
Also use https ... It's permitted only over https


text:
Q: what is the difference between Callable statement and Prepared Statement in Sql? Can anyone please explain the difference between Callable and Prepared Statement in Sql with any example?

A: At the top level you can go by this thought
Prepared Statement
Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared"
Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects.
The prepared statement is used to execute sql queries
Callable Statement
A CallableStatement object provides a way to call stored procedures in a standard way for all RDBMSs. A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains.


text:
Q: Detect on calloutAccessoryControlTapped only the tap on rightCalloutAccessoryView My calloutAccessoryControlTapped is also called when I just tap on annotation view and this behavior it's right. But how can I detect if the user has tapped on the right accessory view (in my case a detail disclosure button) and not just in the view?
I added a simple check but it doesn't work.
import UIKit
import MapKit

extension MapVC: MKMapViewDelegate, CLLocationManagerDelegate
{
    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl)
    {
        if control == view.rightCalloutAccessoryView
        {
            ... // enter here even if I tapped on the view annotation and not on button
        }
    }

}

A: To achieve it you would need to add target for the right accessory view. You can achieve it by setting button to rightCalloutAccessoryView as shown in the code snippet.
class MapViewController: UIViewController, MKMapViewDelegate {

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is Annotation {
            let annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
            let rightButton = UIButton(type: .DetailDisclosure)
            rightButton.addTarget(self, action: #selector(didClickDetailDisclosure(_:)), forControlEvents: .TouchUpInside)
            annotationView.rightCalloutAccessoryView = rightButton
        }
        return nil
    }

    func didClickDetailDisclosure(button: UIButton) {
        // TODO: Perform action when was clicked on right callout accessory view.
    }
}

// Helper classes.
class Annotation: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}

class AnnotationView: MKAnnotationView {

}

A: *

*Using UIView and UITapGestureRecognizer instead of UIControl
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
  let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
  let gestureView = UIView(frame:CGRect(x: 0,y: 0,width: 20,height: 20))
  let gestureRecognizer = UITapGestureRecognizer()
  gestureRecognizer.addTarget(self, action:  #selector(MapViewController.didClickGestureRecognizer(_:)))

  gestureView.addGestureRecognizer(gestureRecognizer)
  gestureView.backgroundColor = UIColor.redColor()
  annotationView.rightCalloutAccessoryView = gestureView
  return annotationView
}

func didClickGestureRecognizer(sender:UITapGestureRecognizer) -> Void {
  print("didClickGestureRecognizer")
}

When you click on rightCalloutAccessoryView, only didClickGestureRecognizer will be called,but your calloutAccessoryControlTapped cannot be invoked anyone.
2.If you have a UIControl as rightCalloutAccessoryView,you can tap directly on MKAnnotationView.Otherwise MKAnnotationView cannot be tapped.
Both your selector and calloutAccessoryControlTapped will be called when you tap rightCalloutAccessoryView or tap directly on MKAnnotationView
3.If you have a UIControl as leftCalloutAccessoryView,both your selector and calloutAccessoryControlTapped will be called when you tapped on it.
4.Since iOS 9,you can has a detailCalloutAccessoryView in your MKAnnotationView.Only your selector will be called when you tapped on it.
5.Also you can create your own custom MKAnnotationView,and change its behaviors.


text:
Q: Something like the trace of a tensor I'm going through some Lorentzian geometry and had some questions about different ways of getting a scalar out of a $(0, 2)$-tensor. Let us denote it by $T_{ab}$. Suppose we're on a pseudo-Riemannian manifold $(M, g)$ of dimension $n + 1$. The most (?) natural way of getting a scalar out of $T$ is the trace:
$$
\text{tr}T = g^{ab}T_{ab}.
$$
In GR I often see a different scalar appearing, namely
$$
T_{ab}T^{ab}.
$$
Is there a name for this operation? Is it just contraction of $T$ with its dual? Is there some way of understanding it as a norm, or anything like that?
Second: Is there a relationship between this scalar and $\text{tr}T$?
Finally, what is meant by $|T|$? I see this appearing in some papers.
Any help is much appreciated!

A: A Riemannian metric is, among other things, an inner product on $(1,0)$ tensors (i.e. tangent vectors).
$$
\langle u,v\rangle=g_{ab}u^av^a\ \ \ \ \ \ \ u,v\in T^1_0M
$$
This generalizes naturally to an inner product on tensors of any rank, given by
$$
\langle U,V\rangle=g_{a_1c_1}\dots g_{a_kc_k}g^{b_1d_1}\dots g^{b_ld_l}U^{a_1\dots a_k}{}_{b_1\dots b_l}V^{c_1\dots c_k}{}_{d_1\dots d_l}
$$ $$
U,V\in T^k_l M
$$
The expression you write down is just $\langle T,T\rangle$, which we may also write as $\|T\|^2$ where $\|\ \ \|$ is the norm induced by the inner product.
The symbol $|T|$ may denote the above norm, but not always. For example, it's common to write the Riemannian volume form as
$$
dV_g=\sqrt{|g|}\ dx^1\wedge\dots\wedge dx^n
$$
Here $|g|$ denotes the absolute value of the determinant of the coordinate representation of $g$. This "determinant" is coordinate dependent, and is frequently used when writing integral expressions in coordinates.

A: We can look at this question in a slightly more general situation, where on a manifold $M$ of dimension $d$ we are given a non-degenerate symmetric $(0,2)$-tensor $g_{ab}$, and a $(0,2)$-tensor $T_{ab}$. Here I use the so-called abstract index notation. The non-degeneracy of $g_{ab}$ means that there is a $g^{ab}$ such that $g_{ac}g^{cb} = \delta_a{}^b$ (the Kronecker symbol, representing the identity map $\delta_a{}^b \colon V^a \to V^b$ where for the moment let $V^a$ be the tangent bundle of $M$).
So, what can we potentially make out of tensor $T$ using only the given structure $g$?
Naturally, we would like to keep things within certain computability constraints and decide to restrict our freedom to all sorts of finite linear combinations of partial contractions which have the following form:
$$
g_{ab} \dots g_{cd} g^{ef} \dots g^{kl} T_{rs} \dots T_{pq}
$$
where some of the upper indices may coincide with some lower indices whenever it makes sense.
Some examples of such contractions would be the corresponding linear transformation $T \colon V \to V$ given by $T_a{}^b = g^{bc} T_{ac}$, its trace $\mathrm{T} := T_a{}^a$, which is the same as $\mathrm{tr_g}T = g^{ab}T_{ab}$, the square of $T$ given by $(T^2)_a{}^b = T_a{}^c T_c{}^b$, and so on.
In particular, we obtain a sequence $T^k$ of powers of $T$:
$$
(T^0)_a{}^b := \delta_a{}^b, (T^{k+1})_a{}^b := (T^k)_a{}^cT_c{}^b,k \ge 0
$$
Notice, that all these considerations are essentially the multi-linear algebra. We proliferate some quantities from tensor spaces over $M$, which are known to be not irreducible. I will not go into full details here (my goal is to give you some hints), but let me just mention that
$$
t_{ab} = t_{[ab]} + t_{(ab)} = t_{[ab]} + t_{(ab)_{0}} + \tfrac{\mathrm{tr}t}{d}g_{ab}
$$
for any tensor $t_{ab}$. Here $t_{(ab)} := \tfrac{1}{2}(t_{ab} + t_{ba})$ and $t_{[ab]} := \tfrac{1}{2}(t_{ab} - t_{ba})$ are the symmetric and the anti-symmetric parts of $t_{ab}$, and $t_{(ab)_{0}} := t_{(ab)}-\tfrac{\mathrm{tr}t}{d}g_{ab}$ is the trace-free part of $t_{(ab)}$.
Furthermore, only a finite number of the powers $T^k$ are linearly independent. This fact is known as the Cayley-Hamilton theorem (in disguise). In order to see this in a slick way, one exploits the fact that in dimension $d$ any anti-symmetric $(0,d+1)$-tensor vanishes identically. Thus, we can look at
$$
0 = T_{[{a_1}}{}^{a_1} \dots T_{{a_d}}{}^{a_d} \delta_{{a_{d+1}}]}{}^{a_{d+1}}
$$
and expand it to see the terms.
Personally, I would call $T_{ab} T^{ab}$ the trace of the square of $T$ and denote it  as $\mathrm{tr} T^2$ or, more rigorously, as $\mathrm{tr_g} (T^2)$. Hence, the length (or norm) of $T$ is given by the formula $|T| = \sqrt{\mathrm{tr_g} (T^2)}$.
There are relationships between $\mathrm{tr_g} (T)$, $\mathrm{tr_g} (T^2)$, and other scalars, such as $\det{T}$. These relationships come from the Cayley-Hamilton identity, and therefore, dimensionally-dependent.
You can find more examples and explanations in my other answers, e.g. here, where I mention a relationship between the quantities in question for the case of dimension $2$:
$$
(\mathrm{tr}T)^2 - \mathrm{tr}(T^2) = 2\,\det T
$$


text:
Q: Spying or Identification tool IN RPA Actually , what is going on background, when we are spying elements or identifying elements. I need some technical answers and difference between the modes available in BP????

A: To get a better understanding of spying the elements try to observe the attributes. The element we spy is identified by its location (Path), size, value, type etc. in HTML, Win32, AA modes. but, this is completely different in Region mode. region mode just takes elements as part of a screen.


text:
Q: About Loading image in Webpage I want to add a spinner to show that the content is loading, when someone clicks on an icon. Basically when someone clicks the hyper-link, the page takes time to load and meanwhile I want to show a spinner/'loading image'. How to implement that?
Thanks in advance
My HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="shortcut icon" type="image/x-icon" href="images/fav-icon.png" />
  <link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
  <meta name="keywords" content=" my webpage" />

            Directory

             News

            View Pay

A: You can try something like below:
1) Place "spinning wheel" image in one div.
2) Add "Loading..." text
When your page is loading set that div to display and once your page is loaded successfully set div to display: none.

            Loading...

UPDATE
When you are clicking on Image button do not directly call server side function. Instead call a client side function like "CallServerSideFunction()" and from that function call your server side function. You can try something like below:
In Javascript function:
 function DisplayProgress() {
        document.getElementById('progressIndicator').style.display = '';
    }

function HideProgress() {
        document.getElementById('progressIndicator').style.display = none;
    }

function CallServerSideFunction() {
        DisplayProgress();
        document.getElementById("btnCallServerSideFunction").click();
        HideProgress();
   }

Let me know if this helps.


text:
Q: prudentia path weirdness: Can't find box using path relative to the current directory Prudentia cannot find the box I defined. I am quite sure that the box is there. And when I use an absolute path it complains about the $prudentia_dir in Ansible.
Here's my directory tree:
deployment/
|-- Readme.md
|-- boxes
|   |-- common_vars.yml
|   |-- dev.yml
|   |-- dev_vars.yml
|   |-- enable_cd.yml
|   |-- staging.yml
|   `-- staging_vars.yml
`-- components
    |-- api.yml
    |-- base.yml
    |-- client.yml
    |-- files
    |   `-- ssh
    |       |-- id_rsa
    |       `-- id_rsa.pub
    |-- mongo.yml
    `-- templates
        |-- api
        |   |-- logback.xml.j2
        |   `-- upstart.conf.j2
        `-- client
            `-- nginx.conf.j2

When I start Prudentia SSH and try to register a box:
(Prudentia > Ssh) register
Specify the playbook path: deployment/boxes/staging.yml
25-06-2014 18:48:35.339 [root] ERROR: Box not added.
Traceback (most recent call last):
  File "/Users/rob/tmp/prudentia/src/ssh.py", line 26, in register
    hostname = self.fetch_box_hostname(playbook)
  File "/Users/rob/tmp/prudentia/src/simple.py", line 202, in fetch_box_hostname
    with open(playbook, 'r') as f:
IOError: [Errno 2] No such file or directory: 'deployment/boxes/staging.yml'

There was some problem while adding the box: [Errno 2] No such file or directory: 'boxes/staging.yml'

After a few attempts with different assumptions on what the relative path should be, I decided to use the absolute path. On that attempt the following error occurs:
(Prudentia > Ssh) register
Specify the playbook path: /Users/rob/......./deployment/boxes/staging.yml
Specify the box name [default: acme-staging]:
Specify the address of the instance: poc01
Specify the remote user [default: rob]: pocuser
Specify the password for the remote user [default: ssh key]:
25-06-2014 18:50:07.654 [root] ERROR: Box not added.
Traceback (most recent call last):
  File "/Users/rob/tmp/prudentia/src/ssh.py", line 33, in register
    self.add_box(box)
  File "/Users/rob/tmp/prudentia/src/simple.py", line 164, in add_box
    self.load_tags(box)
  File "/Users/rob/tmp/prudentia/src/simple.py", line 180, in load_tags
    play = Play(playbook, playbook.playbook[0], dirname(b.playbook))
  File "/Users/rob/tmp/prudentia/p-env/lib/python2.7/site-packages/ansible/playbook/play.py", line 152, in __init__
    self._tasks      = self._load_tasks(self._ds.get('tasks', []), load_vars)
  File "/Users/rob/tmp/prudentia/p-env/lib/python2.7/site-packages/ansible/playbook/play.py", line 588, in _load_tasks
    loaded = self._load_tasks(data, mv, default_vars, included_sudo_vars, list(included_additional_conditions), original_file=include_filename, role_name=new_role)
  File "/Users/rob/tmp/prudentia/p-env/lib/python2.7/site-packages/ansible/playbook/play.py", line 583, in _load_tasks
    data = utils.parse_yaml_from_file(include_filename, vault_password=self.vault_password)
  File "/Users/rob/tmp/prudentia/p-env/lib/python2.7/site-packages/ansible/utils/__init__.py", line 551, in parse_yaml_from_file
    raise errors.AnsibleError("file could not read: %s" % path)
AnsibleError: file could not read: /Users/rob/dev/...../components/$prudentia_dir/tasks/mongodb.yml

There was some problem while adding the box: file could not read: /Users/rob/...../deployment/components/$prudentia_dir/tasks/mongodb.yml

After that Prudentia bails out and fails with the same error on each attempt to start it again.
It seems that there are some assumptions in Prudentia as to how it wants to be used, I do not understand. Please help to 1) fix my situation (failing Prudentia) and 2) prevent it from happening again.

A: Take a look inside your staging.yml. Paths there should be specified in this format:
"{{prudentia_dir}}/tasks/common-setup.yml"
rather than:
$prudentia_dir/tasks/common-setup.yml
Probably you're using box file from previous versions with newer prudentia version.

A: Using the absolute path of the playbook is definitely the right thing to use when registering a new box, we'll make it the question more explicit in the next release.
Regarding the other problem @DmitryEvsee is right, and the issue is due to updates part of Ansible 1.6.
For more information http://docs.ansible.com/playbooks_variables.html#using-variables-about-jinja2.

A: I've had a similar problem:
File "/Users/iwein/projects/prudentia/p-env/lib/python2.7/site-packages/ansible/utils/__init__.py", line 551, in parse_yaml_from_file
raise errors.AnsibleError("file could not read: %s" % path)

ansible.errors.AnsibleError: file could not read: /Users/iwein/projects/…/deployment/boxes/$prudentia_dir/tasks/common-setup.yml
I edited ~/projects/prudentia/env/ssh/.boxes.json (that's where my prudentia checkout is) and removed everything. Then prudentia ran happilly.
Next I registered the … box but it was complaining again:
There was some problem while adding the box: file could not read: /Users/iwein/projects/…/deployment/boxes/$prudentia_dir/tasks/common-setup.yml

Then I modified the box definition yml file to use "{{prudentia_dir}}/whatever" instead of $prudentia_dir. I also had to modify some of the components I used. I used this replace pattern: :%s/\$([^/]*)(.*)/"{{$1}}$2"/g
After that everything should be peachy.