text:
Q: Turn-by-turn direction using PgRouting How can I generate turn-by-turn directions using PgRouting?
At the moment, I have a web-page where a user can enter and start/end location and a route is generated on a map (using PgRouting and OpenStreeMap). I know how to list all of the street names, but I don't know what the best approach for stating which direction the user should take at intersections.
I have read through previous questions on this site:
Does pgRouting support turn-by-turn routing? and How to emulate Google Maps driving directions using pgRouting? but both of these questions are over two years old, and several of the answers link to sites that no longer exist.

A: You already link to two other questions, which are more or less the same, so you will hardly get a different answer.
In short:  you may want to group your route by street names, then calculate the angle and direction between streets, and depending on their values return text instructions or images.

A: I'm not a programmer so I borrowed the following from stack overflow
 after a google search : )
"If you want the direction between to geopoints you have to calculate it. First you need to get the difference of the north/south direction and the the difference of the eas/west direction. Then you can calculate the angle between the two geopoints by using the atan2.
double north_south = point1.getLatitude() - point2.getLatitude();
double east_west = point1.getLongitude() - point2.getLongitude();
int angle = (int) (Math.atan2(east_west, north_south) /
            Math.PI * 180.0 + 360.0f);This is how you get the direction between 2 points (in degrees). If you want to navigate the user, you have to write a whole navigation software, which is far more complicated.
share|improve this answer answered Nov 7 '11 at 15:58
Franziskus Karsunke"


text:
Q: Iterate and modify Struct in a Set I have a Set of Ints:
var mySet = Set<Int>()

mySet.insert(1)
mySet.insert(2)
// ....

// How to iterate over it and, for example, add 1 to each element?
for (index, _) in mySet.enumerated() {
    // How to subscript? A set is unordered!
}

I want to modify mySet and do some extra calculations on it. How can I make modify each element in mySet? I can create another temp mySet Set and add copies to that Set and later on, assign the temp mySet Set to the original mySet, but I was wondering if there was another better way.
// Ugly method?
var mySetTemp = Set<Int>()

for value in mySet {
    mySetTemp.insert(value + 1)
}

mySet = mySetTemp

Is there a way I can do above without creating extra objects, just for the sake of modifying an original value in an iteration of a Set of Structs?
When the Set was an Array, I could easily do it by subscripting elements by index, but since Sets are unordered, I can not do it.

A: You can assign mySet as mapped mySet converted to Set
mySet = Set(mySet.map { $0 + 1 })

redpajama_set_name: RedPajamaStackExchange


text: Q: Can we still use "detect" if there is only one subject When we say we have detected the faulty model does it imply there are more than one model in front of us, and we want to pick the faulty ones? In other words, would it still be appropriate to use "detect" if there is only one model in front of us? or maybe identify is a better word?


text:
Q: Connecting Presto to Kafka does fails - Catalog 'kafka' does not exist I tried to do something similar as the instructions outlined here. Just in my case I wanted to start presto and kafka in docker using docker-compose.
So my docker-compose.yaml looks like this:
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - 22181:2181
    networks:
      - shared
  kafka1:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka1:9092,PLAINTEXT_HOST://localhost:29092,LISTENER_DOCKER_INTERNAL://kafka1:19092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,LISTENER_DOCKER_INTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    networks:
      - shared
  kafdrop:
    image: obsidiandynamics/kafdrop:latest
    restart: "no"
    ports:
      - "8089:9000"
    environment:
      KAFKA_BROKERCONNECT: "kafka1:19092"
    depends_on:
      - "kafka1"
    networks:
      - shared
  presto:
    image: ahanaio/prestodb-sandbox:latest
    ports:
      - 8087:8080
    volumes:
    - ./presto/kafka.properties:/etc/catalog/kafka.properties
    networks:
      - shared
networks:
  shared:
    name: kappa-playground
    driver: bridge

The mounted file kafka.properties has the following content:
connector.name=kafka
kafka.nodes=kafka1:19092
kafka.table-names=example_topic

I ensure kafka has the topic create with the following little script:
# requires kafka-python
from kafka import KafkaClient
from kafka.admin import KafkaAdminClient, NewTopic

client = KafkaClient(bootstrap_servers='localhost:29092')
admin_client = KafkaAdminClient(
    bootstrap_servers="localhost:29092",
    client_id='setup'
)
future = client.cluster.request_update()
client.poll(future=future)
metadata = client.cluster
topics = metadata.topics()
if(len(topics) > 0 ):
    print("topics: " + " ".join(topics))
else:
    print("no topics exist yet")
if("example_topic" not in topics):
    topic_list = []
    topic_list.append(NewTopic(name="example_topic", num_partitions=1, replication_factor=1))
    admin_client.create_topics(new_topics=topic_list, validate_only=False)

I can verify the topic "example_topic" exists with kafdrop.
Now I try to verify that presto can ready the topics from kafka like this:
presto --server=localhost:8087 --catalog kafka --schema default
presto:default> SHOW TABLES;

Which shows the following error:
Query 20220622_080948_00005_t2k7a failed: line 1:1: Catalog 'kafka' does not exist

What is going wrong here?

A: Found the issue. The kafka.properties file was mounted to the wrong path.
It should rather be:
  presto:
    image: ahanaio/prestodb-sandbox:latest
    ports:
      - 8087:8080
    volumes:
    - ./presto/kafka.properties:/opt/presto-server/etc/catalog/kafka.properties
    networks:
      - shared


text:
Q: how to disable specific dates in calendar using android dialog datepicker i want to disable specific dates in calendar.I am using android dialog datepicker.can any one help me please.thank you in advance.i have tried alot but did not find correct solution
am using this for disable  aleredy booked slots
my code:
 public class CalendarActivity extends AppCompatActivity implements
            View.OnClickListener {

        Button btnDatePicker, btnTimePicker;
        EditText txtDate, txtTime;
        private int mYear, mMonth, mDay, mHour, mMinute;
        int day=24;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.calendar_layout);
            Toast.makeText(this,String.valueOf(System.currentTimeMillis()), Toast.LENGTH_LONG).show();
            btnDatePicker=(Button)findViewById(R.id.btn_date);
            btnTimePicker=(Button)findViewById(R.id.btn_time);
            txtDate=(EditText)findViewById(R.id.in_date);
            txtTime=(EditText)findViewById(R.id.in_time);

            btnDatePicker.setOnClickListener(this);
            btnTimePicker.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {

            if (v == btnDatePicker) {

                // Get Current Date
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {

                                txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                            }
                        }, mYear, mMonth, mDay);

   c.add(Calendar.MONTH,1);
            long afterOneMonthsinMilli=c.getTimeInMillis();
            datePickerDialog.getDatePicker().setMaxDate( afterOneMonthsinMilli );
            datePickerDialog.show();

                datePickerDialog.show();
            }
            if (v == btnTimePicker) {

                // Get Current Time
                final Calendar c = Calendar.getInstance();
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);

                // Launch Time Picker Dialog
                TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {

                                txtTime.setText(hourOfDay + ":" + minute);
                            }
                        }, mHour, mMinute, false);
                timePickerDialog.show();
            }
        }
    }


text:
Q: Is there a way to configure the Auto Scaling Group termination policy when using Elastic Beanstalk? The ASG part of Beanstalk options does not have it listed: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html?shortFooter=true#command-options-general-autoscalingasg - and neither does the rest of the page.
Right now I'm having to resort to manually editing the termination policy in the ASG page in EC2.

A: The following works for me. I use .ebextensions folder to configure my apps. Inside I have created a termination.config file containing this:
Resources:
      AWSEBAutoScalingGroup:
        Type: "AWS::AutoScaling::AutoScalingGroup"
        Properties:
          TerminationPolicies: [ "OldestInstance" ]


text:
Q: Magento 1.7: I can't stop reindex process I'm trying to separate magento back end and front end in 2 nodes. I follow the HOW-TO on magento site. Now I have two installation of magento that work properly. My problem comes when  magento start reindex process. It doesn't stop, it's in pending state since friday (5 days).
I try to stop it by removing all locks file in /var/locks folder and restarting apache, but nothing has changed. Now I can't restart it because magento throw me an exception because reindex is in progress and I can't install any extension.
How can I restore the state of reindex process?

A: Make sure that the var/locks folder you are clearing is under your Magento root dir and not simply your base linux var folder.


text:
Q: The type name 'Create' does not exist for type Aes I get an error in VS Code (running on Ubuntu) in the following code
class Program
{
    public static void Main()
    {
        string originalText = "Test";

        try
        {
            using (Aes myAes = new Aes.Create())
            {

                string encrypted = StringCipher.Encrypt(originalText, myAes);
                string decrypted = StringCipher.Decrypt(encrypted, myAes);

                Console.WriteLine(String.Format("Original {0}", originalText));
                Console.WriteLine(String.Format("Encrypted {0}", encrypted));
                Console.WriteLine(String.Format("Decrypted {0}", decrypted));

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadKey();
    }
}

The VS Code intellisense is stating that type name 'Create' doesn't exist in type Aes.
Not sure if it's my bad coding but I am essentially following the guide here.
The only difference being I have implemented the encryption / decryption is being implemented in a separate code file here:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;

namespace EncryptionConsole
{
    public static class StringCipher
    {

        public static string Encrypt(string plainText, Aes aes)
        {

                    // Encrypt the string to an array of bytes.
                    byte[] encrypted = EncryptStringToBytes_Aes(plainText, aes.Key, aes.IV);
                    string result = Encoding.UTF8.GetString(encrypted);
                    return result;

        }

        public static string Decrypt(string cipherText, Aes aes)
        {
            byte[] cipherTextArray = Encoding.UTF8.GetBytes(cipherText);

                // Decrypt the bytes to a string.
                string roundtrip = DecryptStringFromBytes_Aes(cipherTextArray, aes.Key, aes.IV);
                return roundtrip;
        }

        static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

        static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }

    }
}

I appreciate there may be some glaring mistakes in the above code, this is not really of a concern as I am just exploring at this point.
Any help is greatly appreciated.

A: Aes.Create() is a static method. You do not need to instanciate it by using the keyword new. If you look at the docs (https://msdn.microsoft.com/en-us/library/bb351532(v=vs.110).aspx), you will see that this method actually returns a newly created AES object for you. This is referred to as "Static Factory Method" in programming terms, and is a common practice/pattern for initializing objects.

A: Basically calling Aes myAes = new Aes.Create() will try to instanciate the class Create from the namespace or class Aes which explains the error you experience. As stated above you can just use Aes myAes = Aes.Create().


text:
Q: Can not execute insert query? Can you help me solve this problem? im trying to insert data to my database but instead of inserting it die() output; appears
<?php
    if (isset($_GET['submit'])) {
        $item_code = mysqli_real_escape_string($conn, $_GET['item_code']);
        $item_name = mysqli_real_escape_string($conn, $_GET['item_name']);
        $supplier = mysqli_real_escape_string($conn, $_GET['supplier_name']);
        $brand = mysqli_real_escape_string($conn, $_GET['brand_name']);
        $quantity = mysqli_real_escape_string($conn, $_GET['quantity']);
        $unit = mysqli_real_escape_string($conn, $_GET['unit_name']);
        $price = mysqli_real_escape_string($conn, $_GET['price']);
        $item_type = mysqli_real_escape_string($conn, $_GET['type_name']);
        $category = mysqli_real_escape_string($conn, $_GET['cat_name']);

        if ($item_code == '' || $item_name == '' || $supplier == '' || $brand == '' ||
            $quantity == '' ||
            $unit == '' ||
            $price == '' ||
            $item_type == '' ||
            $category == ''
        ) {
            header("Location: item.php?attempt=empty");
        } else {
            $sql = mysqli_query($conn, "INSERT INTO itemlist (item_name,supplier_name,brand_name,quantity,unit_name,price,type_name,cat_name)    values('$item_name','$supplier','$brand','$quantity','$unit','$price','$item_type','$category')")

            or die("Could not execute the insert query.");
            header("Location: item.php?attempt=saved");
        }
    }
?>

A: I just notice things:

*

*Why use GET method to pass data instead of POST?

*You can use empty() instead of == ''

*You can try prepared statement rather than escaping and sanitizing each submitted data

*What is the purpose of $_GET['item_code']? You did not use it in your insert, but it is in your if() condition.

Assuming you changed your form from GET to POST method:
if (isset($_POST['submit'])) {

    if(empty($_POST['item_code']) || empty($_POST['item_name']) || empty($_POST['supplier_name']) || empty($_POST['brand_name']) || empty($_POST['quantity']) || empty($_POST['unit_name']) || empty($_POST['price']) || empty($_POST['type_name']) || empty($_POST['cat_name'])){

        header("Location: item.php?attempt=empty");

    } else {

        $stmt = $conn->prepare("INSERT INTO itemlist (item_code, item_name, supplier_name, brand_name, quantity, unit_name, price, type_name, cat_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssssss", $_POST['item_code'], $_POST['item_name'], $_POST['supplier_name'], $_POST['brand_name'], $_POST['quantity'], $_POST['unit_name'], $_POST['price'], $_POST['type_name'], $_POST['cat_name']);
        $stmt->execute();
        $stmt->close();

        header("Location: item.php?attempt=saved");
    }
}

Remember, one empty data will go inside the if() condition and execute the header("Location: item.php?attempt=empty");.

A: 1)  Add item_code in your insert query.
<?php
    if (isset($_GET['submit'])) {
        $item_code = mysqli_real_escape_string($conn, $_GET['item_code']);
        $item_name = mysqli_real_escape_string($conn, $_GET['item_name']);
        $supplier = mysqli_real_escape_string($conn, $_GET['supplier_name']);
        $brand = mysqli_real_escape_string($conn, $_GET['brand_name']);
        $quantity = mysqli_real_escape_string($conn, $_GET['quantity']);
        $unit = mysqli_real_escape_string($conn, $_GET['unit_name']);
        $price = mysqli_real_escape_string($conn, $_GET['price']);
        $item_type = mysqli_real_escape_string($conn, $_GET['type_name']);
        $category = mysqli_real_escape_string($conn, $_GET['cat_name']);

        if ($item_code == '' || $item_name == '' || $supplier == '' || $brand == '' ||
            $quantity == '' ||
            $unit == '' ||
            $price == '' ||
            $item_type == '' ||
            $category == ''
        ) {
            header("Location: item.php?attempt=empty");
        } else {
            $sql = mysqli_query($conn, "INSERT INTO itemlist (item_code,item_name,supplier_name,brand_name,quantity,unit_name,price,type_name,cat_name)    values('$item_code','$item_name','$supplier','$brand','$quantity','$unit','$price','$item_type','$category')")

            or die("Could not execute the insert query.");
            header("Location: item.php?attempt=saved");
        }
    }
?>

2) Another way to solve it is to define your item_code as primary key.
3) Other way is to define item_code with any default value like 0.

A: You can try this Solution:
function escape($col, $conn) {
    return mysqli_real_escape_string($conn, $_GET[$col]);
}

function insert($tbl, $dataArray) {
    foreach ($dataArray as $k => $v) {
        $keys .= $k . ", ";
        $values .= "'" . $this->real_escape_string($v) . "', ";
    }

    $keys = substr($keys, 0, strlen($keys) - 2);
    $values = substr($values, 0, strlen($values) - 2);
    $sql = "INSERT INTO " . $tbl . "(" . $keys . ") VALUES(" . $values . ")";
    $exeq = mysqli_query($sql);
    return $exeq;
}

$fields = array("item_code", "item_name", "supplier_name", "brand_name", "quantity", "unit_name", "price", "type_name", "cat_name");

if (isset($_GET['submit'])) {
    $item_code  = escape('item_code', $conn);
    $item_name  = escape('item_name', $conn);
    $supplier   = escape('supplier_name', $conn);
    $brand      = escape('brand_name', $conn);
    $quantity   = escape('quantity', $conn);
    $unit       = escape('unit_name', $conn);
    $price      = escape('price', $conn);
    $item_type  = escape('type_name', $conn);
    $category   = escape('cat_name', $conn);

    foreach ($fields as $field) {
        if (!$_GET[$field]) {
            header("Location: item.php?attempt=empty");
        }
    }

    $dataInsert = array(
        'item_code'     => $item_code,
        'item_name'     => $item_name,
        'supplier_name' => $supplier,
        'brand_name'    => $brand,
        'quantity'      => $quantity,
        'unit_name'     => $unit,
        'price'         => $price,
        'type_name'     => $item_type,
        'cat_name'      => $category
    );

    if ( insert("itemlist", $dataInsert) ) {
        header("Location: item.php?attempt=saved");
    } else {
        echo "Could not execute the insert query.";
        exit();
    }
}


text:
Q: Relevance percentage( searchstring is more "left" in sourcestring) Can anybody help with selecting of algorithm.
To compare two strings and give a relevance percentage(if more left found, more rank).
maybe merge two algorithms
for example:
looking for "chocolate white quills"
we have records
CHOCOLATE, WHITE/DARK QUILLS [MONA LISA, 4 #/CS]
CHOCOLATE, WHITE QUILLS [SWISS CHALET, 900 GR BOX]
PASTRY INGR., CHOCOLATE QUILLS WHITE [SWISS CHALET FINE FO, 16 / 120 CT]

the result must be like this:
CHOCOLATE, WHITE QUILLS [SWISS CHALET, 900 GR BOX] | 0,1
CHOCOLATE, WHITE/DARK QUILLS [MONA LISA, 4 #/CS] | 0,2
PASTRY INGR., CHOCOLATE QUILLS WHITE [SWISS CHALET FINE FO, 16 / 120 CT] | 0,4

like you can see it is not strong compare must be used
I'm now use JaroWinkler
and now result like this
CHOCOLATE, WHITE/DARK QUILLS [MONA LISA, 4 #/CS] | 0,3775
CHOCOLATE, WHITE QUILLS [SWISS CHALET, 900 GR BOX] | 0,3769
PASTRY INGR., CHOCOLATE QUILLS WHITE [SWISS CHALET FINE FO, 16 / 120 CT] | 0,3728

A: With any ranking of text, you need to be explicit about what you're trying to measure.  In your example
CHOCOLATE, WHITE QUILLS [SWISS CHALET, 900 GR BOX] | 0,1
CHOCOLATE, WHITE/DARK QUILLS [MONA LISA, 4 #/CS] | 0,2
PASTRY INGR., CHOCOLATE QUILLS WHITE [SWISS CHALET FINE FO, 16 / 120 CT] | 0,4

Why is the first item ranked lower than the second?  I sort of understand why the bottom one has the highest rating, because it contains all the items in the string without intermediate strings. Provide some more details and we'll try to help.


text:
Q: How to loop around a circle in c++ Im working on a problem that is called the crazy pet store. Basically there are 35 bowls of fish arranged in a circle in a room. each bowl had a diff type and amount of fish in them. they are arranged as follows:
Bowls 1 – 3: 15 fish
Bowls 4 – 7: 8 fish
Bowl 8: 19 fish
Bowls 9 – 12: 16 fish
Bowls 13 – 22: 14 fish
Bowls 23 – 24: 31 fish
Bowls 25 – 29: 9 fish
Bowls 30 – 33: 26 fish
Bowls 34 – 35: 8 fish

There's a seal who eats a total of 361 fish -- one from every 4th bowl starting with bowl #4, then #8, #12, #16 etc. Im trying to figure out how to calculate the number and type of fish left after the seal eats 361 fish. For some reason the tiger fish calculation is off and I cant figure out why.(the seal isnt eating any tiger fish)Below is my program
int main()
{
    //variable declaration
    int seal, bowl = 0, goldCount = 0, gupCount = 0, angelCount = 0, tigerCount = 0, totalFish = 0, fishEaten = 0, x = 0, num = 0, currentBowl = 3;

    //array with # of fish in bowls
    int fishNum[35] = { 15, 15, 15, 8, 8, 8, 8, 19, 16, 16, 16, 16,
                        14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 31,
                        31, 9, 9, 9, 9, 9, 26, 26, 26, 26, 8, 8 };  // initialize the number of fish in bowls

    //initialize type of fish in bowls
    string fishType[35] = { "goldfish", "goldfish", "goldfish", "goldfish", "goldfish", "goldfish",
                            "guppies", "guppies", "guppies", "guppies", "guppies", "guppies", "guppies",
                            "angel", "angel", "angel", "angel", "angel", "angel", "angel", "angel", "angel",
                            "goldfish", "goldfish", "goldfish", "goldfish", "goldfish", "goldfish", "goldfish", "goldfish",
                            "tiger", "tiger", "tiger", "tiger", "tiger" };

    //THIS ANSWERS QUESTION A1 which lists the # and type of fish in each bowl
    cout << "The number and type of fish in each bowl is as follows: " << endl;
    for (int bowl = 0; bowl <= 34; bowl++)
    {
        num++;
        cout << "Bowl " << num << " - " << fishNum[bowl] << " " << fishType[bowl] << endl;
    }
    //go through array and link fishNum to fishType
    for (int x = 0; x <= 35; x++)
    {
        if (fishType[x] == "goldfish")
            goldCount += fishNum[x];
        else if (fishType[x] == "guppies")
            gupCount += fishNum[x];
        else if (fishType[x] == "angel")
            angelCount += fishNum[x];
        else if (fishType[x] == "tiger")
            tigerCount += fishNum[x];
    }

    //calculates total number of fish
    totalFish = (goldCount + gupCount + angelCount + tigerCount);

    //THIS ANSWERS QUESTION B1
    cout << "\nTo begin, there are " << totalFish << " total fish. There are " << goldCount << " gold fish, "
        << gupCount << " guppies, " << angelCount << " angel fish, and " << tigerCount << " tiger fish." << endl;

    //traverese through bowls in the room
    while (fishEaten < 361)
    {
        {//keeps track of type of fish eaten
        if (fishNum[bowl] > 0)
            if (fishType[bowl] == "goldfish")
                goldCount--;
            else if (fishType[bowl] == "guppies")
                gupCount--;
            else if (fishType[bowl] == "angel")
                angelCount--;
            else
                tigerCount--;
        }
        if (fishNum[bowl] > 0)              //if bowl isnt empty...
        {
            fishNum[bowl]--;                //eat one fish
            fishEaten++;                    //add one to fish eaten tally
            bowl + 4;                       //go to next 4th bowl
        }
        else
        {
            bowl++;                         //if bowl is empty, go to next bowl
        }
        bowl %= 35;                         //wraps around the 35 bowls
    }

    //answer to B2
    cout << "The number of fish eaten is: " << fishEaten << endl;
    cout << "There are " << totalFish - fishEaten << " fish left over once the seal is done eating." << endl;

    //didnt eat any tiger fish
    cout << "\nThere are " << goldCount << " gold fish, " << gupCount << " guppies, " << angelCount << " angel fish, and " << tigerCount << " tiger fish." << endl;

    return 0;
}```

Can anyone point out why the tiger fish calculation isnt working?

A: You want to use the modulo operator, to wrap around. For example:
int bowl = 0;
while (fishEaten < 361)
{
    fishNum[bowl]--;
    fishEaten++;

    bowl = (bowl + 4) % 35; // this goes 4 bowl further, wrapping around
}

If you want to skip empty bowls, just add logic for it:
int bowl = 0;
while (fishEaten < 361)
{
    if (fishNum[bowl] > 0)
    {
        fishNum[bowl]--;
        fishEaten++;
    }

    // advance even if the bowl was empty
    bowl = (bowl + 4) % 35; // this goes 4 bowl further, wrapping around
}


text:
Q: LDAP multiple locations Is there a way to add multiple locations here?  I need to do this for testing purposes and to add ldap filter on multiple locations. Currently, I only have one location. I would like to test with at least two locations.
<Employees FileFormat="LDAP"
             FilePath="LDAP://LDAPS.company:6367"
             Filter="(&(objectClass=user)(objectCategory=person)(givenName=*)(sn=*)(mail=*)(PhysicalDeliveryOfficeName=Test Location))"
             FilterOptions="Subtree">

A: Use the LDAP "or" operator, which is |, like this:
Filter="(&(objectClass=user)(objectCategory=person)(givenName=*)(sn=*)(mail=*)(|(PhysicalDeliveryOfficeName=Test Location)(PhysicalDeliveryOfficeName=Test Location 2)(PhysicalDeliveryOfficeName=Test Location 3)))"

More details about how to build LDAP queries is here: Active Directory: LDAP Syntax Filters


text:
Q: ActiveX asks user to install every time the page loads I have an activeX control, that ask the user if he want's to install it every single time the page loads (Even if it is already installed)...
Can anyone point me in the right direction? What I have tried so far:

*

*Setting new Guids for the class & interface.

*Changing interfaces names & method names.

*Changing version number

*Uninstalling and re-installing the activeX

A: First see this MSDN post it sounds like what you are experiencing.

This can happen when the VerCache
  registry key may not have got updated
  during the upgrade of the control. For
  example,
  [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Settings{D7D5ACA4-
  4C57-4C75-8D68-BC185E924B4C}]
  "VerCache" This happens if the old and
  new versions of the control have the
  same "Created"  date time stamp,
  "Modified" date time stamp and the
  file size.
If this registry key doesn't exist,
  you may have to use the Sysinternals
  Process Monitor tool to log a repro of
  the problem, then search the log for
  the correct registry value that is
  being checked. It's most likely under
  \Ext\Settings{}...but
  regardless, ensure that at least one
  of these parameters - "Created" date
  time stamp, "Modified" date time stamp
  or the file size, on the updated
  control is different from the old
  version of the control.

Also, I would use Process Monitor (Sysinternals) as the user installs the ActiveX control to check that it is making the correct registry entries. Search through the registry for the any GUID's associated with your "old" controls and latest. You may want to backup your registry before actually deleting any registry keys.
You could also try a registry cleaning or search tool.
If these don't help perhaps you could provide some more details about your ActiveX control.

*

*Did you use binary compatability?

*What Version of windows of user?

*Which version of IE of user?

*Is this only happening to this user? (this works for others?)

Did the user re-install any software lately?
How about checking :

*

*The registry (Does your ActiveX make any registry changes?)

*The user's PATH environment variable

Have you had the user unregister the dll? You can run this from the cmd line where the dll file is located on the hard drive:
From the command prompt, type "regsvr32 /u filename.dll" where "filename" is the name of the file that you want to unregister.

A: To solve this I ended up writing a custom installer action which deleted VerCache before and after each install.  I also wrote a really long blog post about it to vent.  Hope this helps someone from falling into the same time sink.

A: In my case the solution was to fix the version of my ActiveX control inside resource file my_active_x_control.rc
I read this blog

Go to any machine and start IE8. Select Tools>Manage Addons then
  select the Show:Downloaded Controls dropdown. to view the list of
  installed Active X controls...

The version of my control was 1.0.0.1. As soon as I updated version inside the resource file continuous installation disappeared.


text:
Q: Can't access jupyter notebook in local vagrant virtualbox via local browser As the title described. I already set the Vagrantfile with:
config.vm.network "forwarded_port", guest: 8888, host: 8888, auto_correct: true

and also set the jupyter_notebook_config.py as:
c.NotebookApp.port = 8888

When I activate the notebook in vagrant virtualbox the displayed info was normal:

But local browser (Safari) can't access to it by any means.

A: I stumbled on a issue that seems similar. Here is what solved it for me:

*

*In the Vagrantfile, I added:
config.vm.network "private_network", ip: "192.168.33.10"

*From the vagrant virtual machine start jupyter notebook with:
jupyter notebook --no-browser --ip 0.0.0.0

*Or in the browser of the host access jupyter via 192.168.33.10:8888

A: Your issue is that the server is listening on localhost in the VM so it is only available within the VM.
If you want the server to be available from your host, you should bind the ip to 0.0.0.0
see this thread to understand the differences
Adding the following in your config will do the trick
c.NotebookApp.ip = '0.0.0.0'


text:
Q: How can I make calculations based on smart category summaries in Numbers? The latest version of Numbers has a great feature called Smart Categories that are kind of like Excel's pivot tables. I'm using it to group a table by a label and then sum up spending and revenue numbers.
The next thing I'd like to do is calculate the ratio between these two, i.e. a new column that has the value revenue / spending. How do I do this? If I create a new column, the only options are to use built-in summary functions (see below) - I can't enter my own formula.
Example of smart categories:

Options for "Ratio" column:

A: While it's not (currently) possible to place custom values in the column you desire, it is possible to refer to the operands elsewhere, such as by using a secondary table to refer to the cells in question. To make a formula point to a certain category's subtotal, hold ⌥ option and click on the desired cell.
Unfortunately, this method does require the categories to be entered manually, so it may not be suitable for all situations.
Here is a demonstration using your example table, with a secondary table holding ratio values for each of the categories:

A: It looks like Numbers doesn't yet support custom formulas here. You can reference those cells from other locations, but you can't actually use them for grouping unfortunately.


text:
Q: Bootstrap form input alignment I'm trying to make a responseive form with bootstrap.
Here's what I have at the moment:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <form class='form-horizontal'>

      Product

        <select class='form-control input-lg'>
              <option>
                Device
              </option>
            </select>

        <button type='button' class='btn btn-block btn-default btn-lg'>Manage product
            </button>

      Profile

        <select class='form-control input-lg'>
              <option>123
              </option>
            </select>

        <button type='button' class='btn btn-block btn-default btn-lg'>Manage profile
            </button>

      From

        <input type='date' data-format='yyyy-MM-dd' class='form-control input-lg' value='2018-01-24' />

      To

        <input type='date' data-format='yyyy-MM-dd' class='form-control input-lg' value='2018-01-26' />

        <button type='button' class='btn btn-block btn-primary btn-lg'>Load
            </button>

  </form>

Everything is how I want it, except that on medium devices (>= 992px, col-md-) or bigger I would like the 'From' and 'To' rows next to each other, so that the 'To' would be underneath the 'Manage profile' button. Any ides on how to achieve this?

A: You could combine the last form-group like this..

    <form class="form-horizontal">

            Product

                <select class="form-control input-lg">
                    <option>
                        Device
                    </option>
                </select>

                <button type="button" class="btn btn-block btn-default btn-lg">Manage product
                </button>

            Profile

                <select class="form-control input-lg">
                    <option>123
                    </option>
                </select>

                <button type="button" class="btn btn-block btn-default btn-lg">Manage profile
                </button>

            From

                <input type="date" data-format="yyyy-MM-dd" class="form-control input-lg" value="2018-01-24">

            To

                <input type="date" data-format="yyyy-MM-dd" class="form-control input-lg" value="2018-01-26">

    </form>

https://www.codeply.com/go/FsKzmCSKdq
However, on the last 2 date inputs, they'll be too wide on xs screens so you probably still want those to stack into vertical columns.


text:
Q: How to open a URL in Selenium webdriver other than driver.get() and navigate()? I'm using Selenium webdriver using Java and i know how to open a browser in 2 ways:

*

*driver.get("some url")

*driver.navigate().GoToUrl("some url")
Is there any option available to open a browser other than this?

A: You can use Java script, there is a command window.location='url' which can help you to achieve this.
String url = "https://www.google.com";
String script = "window.location = \'"+url+"\'";
System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
WebDriver driver= new FirefoxDriver();
((JavascriptExecutor) driver).executeScript(script);

But again this is NOT a recommended method.
Difference between get() and this command is that, get() would wait for your page to load but NOT Javascript, it would just do what you command and that's it. You would need to separately manage waits then.
So if possible use the traditional methods. :)


text:
Q: Is it possible to have threads spawned under Unity3D runtime leveraging multi core systems? Phrasing it differently: Can multithreading under Unity's Mono result in parallelism?
Research (based on Samsung Galaxy S5 and iPhone4S profiling):
I tried spawning Unity3D-agnostic threads in C# that carry out some heavier calculations hoping for a parallel execution and performance improvement. I reduced sync operations as much as I could, but I saw no frame rate improvement at all which makes me think everything's still executed on one core. And that's perfectly fine on it's own - after all multi-threading doesn't need to result in parallelism.
But can it result in parallel execution (multi core execution)?
I would love to hear an answer like:

*

*Yes, I am completely positive that under XYZ circumstances your thread can be executed on a separate core. If that's the case:

*

*Can you point to any example?

*How would you measure if other cores are doing relevant work on mobile devices?

*Is there a setting of any kind to enable parallelism? For example defining number of cores that can be used when available (platform specific deployment)

or

*No. You can have multi-threading but no parallelism because XYZ constrains you to multi-threaded but single-core execution.

Answers that don't help:

*

*Yes it's perfectly fine to have Unity agnostic threads executed concurrently - Yup I know, I managed to leverage that, but the question is about parallelism's viability not multi-threading.

*Unity API is not thread safe, be careful - Yup, that's true, thank you.

*Please post an example of how you carried out your research - Maybe you are right and I am missing something, but I think that the main question is a yes/no question. Given strong motivation i am perfectly happy with that sort of answer. I believe example would be a bit involved and would obscure the main question, so for now I would prefer not to post examples.

*You can find examples of code written with parallelism in mind on MSDN - that's true, however most of features supporting parallelism were introduced in .NET 4.0, we are talking about Mono 2.0 and there may be some additional platform specific constraints.


text:
Q: python3 How to select two elements on either side of a random element in a list? I have finished this part of the code so far:
wedding = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
from random import randrange
random_index = randrange(0, len(wedding))
print('TV =', wedding[random_index])

I got stuck at a step that I need to find two elements on either side of the element that I have randomly selected.

A: When using arrays, always check for your array bounds in your code. The below code will output the value from the array that is to the left and right of the randomly selected index value. If either of the indexes are out of bounds, it will not output that value.
from random import randrange

wedding = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_index = randrange(0, len(wedding))

print('TV = ', wedding[random_index])

if random_index-1 >= 0:
    print('Left of Index = ', wedding[random_index-1])
if random_index + 1 < len(wedding) - 1:
    print('Right of Index = ', wedding[random_index + 1])


text:
Q: Avoiding timeout on container-managed EntityManager I have an J2EE application whose beans have container-managed EntityManager's. In long running method calls, trying to merge data throws a

RollbackException (Timed out)

I have tried using an EntityManagerFactory but it doesn't seem to be allowed:

Cannot use an EntityTransaction while using JTA

How can I run arbitrarily long processes without setting an unreasonable timeout? Can't JTA create a new transaction when needed?

A: Following the comments to my question, this question and the documentation here, I solved the problem using a container-managed EntityManager and TransactionAttributeType annotations.
The bean method that caused the timeout now does multiple calls to a different method that handles a subtask, such as each method call executes within a different transaction. I use NOT_SUPPORTED attribute type since:

If the client is not associated with a transaction, the container does not start a new transaction before running the method.

With this arrangement, only the smaller processDoc method creates transactions that shouldn't timeout.
public class MyBean {
    @EJB
    private DocsBean docsBean;

    /**
     * This method transaction risks a timeout
     * so no transaction is created with NOT_SUPPORTED
     */
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void longRunning(List<Document> docs) {
        for (Document doc : docs) {
            // a different transaction is used for each element
            docsBean.processDoc(doc);
        }
    }
}

public class DocsBean {
    /** Runs within a new transaction */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void processDoc(Document document) {
        // takes some time but under the timeout
        // ...
    }
}

.

A: What about using the UserTransaction?
@Resource
private UserTransaction tx;

@TransactionAttribute(TransactionAttributeType.NotSupported)
public void merge(SomeEntity e) {
   tx.setTransactionTimeout(60 * 1000); //one minute
   tx.begin();
   try {
      entityManager.merge(e);
      tx.commit();
   } catch(IllegalArgumentException ex) {
       tx.rollback();
   }
}


text:
Q: Training a tf.keras model with a basic low-level TensorFlow training loop doesn't work Note: All code for a self-contained example to reproduce my problem can be found below.
I have a tf.keras.models.Model instance and need to train it with a training loop written in the low-level TensorFlow API.
The problem:
Training the exact same tf.keras model once with a basic, standard low-level TensorFlow training loop and once with Keras' own model.fit() method produces very different results. I would like to find out what I'm doing wrong in my low-level TF training loop.
The model is a simple image classification model that I train on Caltech256 (link to tfrecords below).
With the low-level TensorFlow training loop, the training loss first decreases as it should, but then after just 1000 training steps, the loss plateaus and then starts increasing again:

Training the same model on the same dataset using the normal Keras training loop, on the other hand, works as expected:

What am I missing in my low-level TensorFlow training loop?
Here is the code to reproduce the problem (download the TFRecords with the link at the bottom):
import tensorflow as tf
from tqdm import trange
import sys
import glob
import os

sess = tf.Session()
tf.keras.backend.set_session(sess)

num_classes = 257
image_size = (224, 224, 3)

# Build a tf.data.Dataset from TFRecords.

tfrecord_directory = 'path/to/tfrecords/directory'

tfrecord_filennames = glob.glob(os.path.join(tfrecord_directory, '*.tfrecord'))

feature_schema = {'image': tf.FixedLenFeature([], tf.string),
                  'filename': tf.FixedLenFeature([], tf.string),
                  'label': tf.FixedLenFeature([], tf.int64)}

dataset = tf.data.Dataset.from_tensor_slices(tfrecord_filennames)
dataset = dataset.shuffle(len(tfrecord_filennames)) # Shuffle the TFRecord file names.
dataset = dataset.flat_map(lambda filename: tf.data.TFRecordDataset(filename))
dataset = dataset.map(lambda single_example_proto: tf.parse_single_example(single_example_proto, feature_schema)) # Deserialize tf.Example objects.
dataset = dataset.map(lambda sample: (sample['image'], sample['label']))
dataset = dataset.map(lambda image, label: (tf.image.decode_jpeg(image, channels=3), label)) # Decode JPEG images.
dataset = dataset.map(lambda image, label: (tf.image.resize_image_with_pad(image, target_height=image_size[0], target_width=image_size[1]), label))
dataset = dataset.map(lambda image, label: (tf.image.per_image_standardization(image), label))
dataset = dataset.map(lambda image, label: (image, tf.one_hot(indices=label, depth=num_classes))) # Convert labels to one-hot format.
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.repeat()
dataset = dataset.batch(32)

iterator = dataset.make_one_shot_iterator()
features, labels = iterator.get_next()

# Build a simple model.

input_tensor = tf.keras.layers.Input(shape=image_size)
x = tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), activation='relu', kernel_initializer='he_normal')(input_tensor)
x = tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), activation='relu', kernel_initializer='he_normal')(x)
x = tf.keras.layers.Conv2D(128, (3,3), strides=(2,2), activation='relu', kernel_initializer='he_normal')(x)
x = tf.keras.layers.Conv2D(256, (3,3), strides=(2,2), activation='relu', kernel_initializer='he_normal')(x)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dense(num_classes, activation=None, kernel_initializer='he_normal')(x)
model = tf.keras.models.Model(input_tensor, x)

This is the simple TensorFlow training loop:
# Build the training-relevant part of the graph.

model_output = model(features)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

train_op = tf.train.AdamOptimizer().minimize(loss)

# The next block is for the metrics.
with tf.variable_scope('metrics') as scope:
    predictions_argmax = tf.argmax(model_output, axis=-1, output_type=tf.int64)
    labels_argmax = tf.argmax(labels, axis=-1, output_type=tf.int64)
    mean_loss_value, mean_loss_update_op = tf.metrics.mean(loss)
    acc_value, acc_update_op = tf.metrics.accuracy(labels=labels_argmax, predictions=predictions_argmax)
    local_metric_vars = tf.contrib.framework.get_variables(scope=scope, collection=tf.GraphKeys.LOCAL_VARIABLES)
    metrics_reset_op = tf.variables_initializer(var_list=local_metric_vars)

# Run the training

epochs = 3
steps_per_epoch = 1000

fetch_list = [mean_loss_value,
              acc_value,
              train_op,
              mean_loss_update_op,
              acc_update_op]

sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())

with sess.as_default():

    for epoch in range(1, epochs+1):

        tr = trange(steps_per_epoch, file=sys.stdout)
        tr.set_description('Epoch {}/{}'.format(epoch, epochs))

        sess.run(metrics_reset_op)

        for train_step in tr:

            ret = sess.run(fetch_list, feed_dict={tf.keras.backend.learning_phase(): 1})

            tr.set_postfix(ordered_dict={'loss': ret[0],
                                         'accuracy': ret[1]})

Below is the standard Keras training loop, which works as expected. Note that the activation of the dense layer in the model above needs to be changed from None to 'softmax' in order for the Keras loop to work.
epochs = 3
steps_per_epoch = 1000

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(dataset,
                    epochs=epochs,
                    steps_per_epoch=steps_per_epoch)

You can download the TFRecords for the Caltech256 dataset here (about 850 MB).
UPDATE:
I've managed to solve the problem: Replacing the low-level TF loss function
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

by its Keras equivalent
loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=labels, output=model_output, from_logits=True))

does the trick. Now the low-level TensorFlow training loop behaves just like model.fit().
This raises a new question:
What does tf.keras.backend.categorical_crossentropy() do that tf.nn.softmax_cross_entropy_with_logits_v2() doesn't that leads the latter to perform much worse? (I know that the latter needs logits, not softmax output, so that's not the issue)

A: Replacing the low-level TF loss function
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

by its Keras equivalent
loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=labels, output=model_output, from_logits=True))

does the trick. Now the low-level TensorFlow training loop behaves just like model.fit().
However, I don't know why this is. If anyone knows why tf.keras.backend.categorical_crossentropy() behaves well while tf.nn.softmax_cross_entropy_with_logits_v2() doesn't work at all, please post an answer.
Another important note:
In order to train a tf.keras model with a low-level TF training loop and a tf.data.Dataset object, one generally shouldn't call the model on the iterator output. That is, one shouldn't do this:
model_output = model(features)

Instead, one should create a model in which the input layer is set to build on the iterator output instead of creating a placeholder, like so:
input_tensor = tf.keras.layers.Input(tensor=features)

This doesn't matter in this example, but it becomes relevant if any layers in the model have internal updates that need to be run during the training (e.g. BatchNormalization).

A: You apply a softmax activation on your last layer
x = tf.keras.layers.Dense(num_classes, activation='softmax', kernel_initializer='he_normal')(x)

and you apply again a softmax when using
tf.nn.softmax_cross_entropy_with_logits_v2 as it expects unscaled logits. From the documentation:

WARNING: This op expects unscaled logits, since it performs a softmax
  on logits internally for efficiency. Do not call this op with the
  output of softmax, as it will produce incorrect results.

Thus, remove the softmax activation of your last layer and it should work.
x = tf.keras.layers.Dense(num_classes, activation=None, kernel_initializer='he_normal')(x)
[...]
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))


text:
Q: PHP MySql -- return all records where column names are unknown I am writing a web service for use in a mobile application. The web service uses a support class that executes a query and returns the results as JSON. I would like to be able to simple return the entire result set as JSON, but "mysql_fetch_array" only returns one record at a time. Furthermore, I will not know the column names, so manually generating the JSON output could be tricky.
So I guess this is a two part question. In .NET, there is a columns collection through which the column names can be acquired. Is there anything like this in PHP? And, how would one return the entire result set as JSON without having to iterate the set and manually build the JSON. THanks! Viv
    public static final function executeSelectQuery($qry){
        $connection = mysql_connect(ADS_DB_HOST, ADS_DB_USERNAME, ADS_DB_PASSWORD) or die(ADS_ERROR_MSG . mysql_error());
        $db = mysql_select_db(ADS_DB_NAME) or die(ADS_ERROR_MSG . mysql_error());
        $result = mysql_query($qry) or die(ADS_ERROR_MSG . mysql_error());
        mysql_close();

        while($rows = mysql_fetch_array(($result))){
            // how do I access column names?
        }
    }

A: public static final function executeSelectQuery($qry){
    $connection = mysql_connect(ADS_DB_HOST, ADS_DB_USERNAME, ADS_DB_PASSWORD) or die(ADS_ERROR_MSG . mysql_error());
    $db = mysql_select_db(ADS_DB_NAME) or die(ADS_ERROR_MSG . mysql_error());
    $result = mysql_query($qry) or die(ADS_ERROR_MSG . mysql_error());
    mysql_close();
    $results = array();
    while($rows = mysql_fetch_assoc(($result))){
        $results[] = $rows;
    }
    return $results;
}

Then to make it into json
$json = json_encode(Classname::executeSelectQuery($qry));

A: You can fetch array using MYSQL_ASSOC option (refer to the manual). In this case your column names are as keys of array, you can retrieve them eg. using array_keys() function.


text:
Q: Why does finding the average in a proc means and a proc sql step yield different results according to a proc compare? I have the following code. The datasets created are test_means and test_sql. Both are taking the simple average of a variable of your choice.
Both create exactly the same number by eye.
Why is it that the proc compare says the values are unequal to a stupidly small value, like 0E-14? Is this something to do with the way numbers are stored in both procedures?
%let var=; *Insert numeric variable to check;
%let dsn=; *Insert dataset name;

proc means noprint mean data=&dsn.;
    var &var.;
    output out=test_means (keep=_STAT_ &var. where=(_STAT_="MEAN"));
run;

proc sql;
    create table test_sql as select
        "MEAN" as _STAT_ length=8,
        mean(&var.) as &var.
    from &dsn.
    ;
quit;

proc compare data=test_means compare=test_sql;
run;

A: Differences on the order of E-14 are to be expected from calculations done on floating point values (as SAS numbers are).  This isn't particularly related to the different PROCs; all it would take would be summing values in a different order to produce an error along those lines.  Even two different runs in PROC SQL could generate differences of this magnitude, if rows end up processed differently (due to multithreading, for example).
PROC COMPARE runs should generally be done with the FUZZ option, unless you are comparing numbers with very small magnitudes.  This should usually be part of standard practice, unless you specifically want to see this kind of difference (meaning, unless you want to verify two files are the same file, and not just the same values).


text:
Q: Using a progress bar in a functional expression If we have a procedural construct like a Do loop or Table, it is straightforward to make a progress bar to indicate the percent completion of the task. For example:
f[k_] := RandomInteger[{-k, k}, 1000000];
ProgressIndicator[Dynamic[k/100]]
Do[f[k], {k, Range[100]}]

Replacing Do by Table works as well. But I have grown fond of the "functional style" using Map:
f[#]& /@ Range[100]

Is there a way to make a progress indicator that works with this style of iteration?

A: You can include an iterator along with the function in the mapping:
k = 0; (++k; f[#]) & /@ Range[100];


text:
Q: How to put a disclosure triangle's title to the right of the triangle? In the HIG's example of how to use disclosure triangles, it shows a label directly to the right of the triangle.
However, when I throw one of these onto my view in Interface Builder, the text is centered on top of the triangle.  I've searched the NSButton API docs, and poked at everything I can find in IB, but nothing I try will put the text to the right of the triangle.  What am I missing?

A: What I generally do is use 2 buttons: one disclosure button and another button for the label:

While you can use a text field for the label, I prefer using a button and setting the button to call performClick: on the disclosure triangle. This makes for a much larger target area to be able to click on than a tiny triangle. (Users with trackpads will thank you).
To set up the button, change it so it looks like this:

Then set its action:

I'm not sure if there's an actual way to get the button to show both properly (without subclassing I mean), since I've generally just used separate items to give the effect. (I just checked and there is indeed a Carbon disclosure control that has both the triangle and the label built-in).
The Carbon control has the right idea where clicking on the label will automatically trigger the control. In some places (notably the re-written Cocoa Finder), you can see that you don't get that behavior for free (unless you use a button like I've shown). I still have an open bug on that one (rdar://6828042): BugID 6828042: 10.6 (10A335) Finder: Inspector's disclsr. triangle's text label not toggleable". ;-)

A: Have you tried just using a triangle and using a separate label?

A: The disclosure triangle widget is drawn by the button's bezel, centered in the available space. To create a disclosure triangle button which also has a title, you just need to subclass NSButtonCell and make sure the bezel is restricted to the left side of the button and that the title avoids the bezel. Then add your button in IB, expand it and set your title, and set the class of the cell. Unfortunately, IB won't know how to display your subclass and will put the triangle in the middle of the button. Just make sure it's big enough.

In Objective-C:
@interface TitledDisclosureTriangleButtonCell : NSButtonCell
@end

#define TRIANGLE_PADDING    15.f

@implementation TitledDisclosureTriangleButtonCell

- (NSRect)titleRectForBounds:(NSRect)theRect
{
    NSRect titleRect = [super titleRectForBounds:theRect];

    titleRect.origin.x = TRIANGLE_PADDING;
    titleRect.size.width = NSWidth(titleRect) - TRIANGLE_PADDING;

    return titleRect;
}

- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView
{
    NSRect bezelFrame = frame;
    bezelFrame.size.width = TRIANGLE_PADDING;

    [super drawBezelWithFrame:bezelFrame inView:controlView];
}

@end

And in Swift:
let TRIANGLE_PADDING: CGFloat = 15

class TitledDisclosureTriangleButtonCell: NSButtonCell
{
    override func titleRectForBounds(theRect: NSRect) -> NSRect {
        var titleRect = super.titleRectForBounds(theRect)

        titleRect.origin.x = TRIANGLE_PADDING
        titleRect.size.width = titleRect.size.width - TRIANGLE_PADDING

        return titleRect
    }

    override func drawBezelWithFrame(frame: NSRect, inView controlView: NSView) {
        var bezelFrame = frame
        bezelFrame.size.width = TRIANGLE_PADDING

        super.drawBezelWithFrame(bezelFrame, inView: controlView)
    }
}


text:
Q: WSO2APIM Message Mediation - API call blocked I am trying to test out XACML policies defined in WSO2 IS through WSO2 API Manager, as explained in the following link
https://docs.wso2.com/display/AM210/Enabling+Role-Based+Access+Control+Using+XACML
The policy is getting validated and I can see the "Permit" decision in the logs, but the API manager doesn't returns any response and the call is blocked and the request gets timed out after some time.
    DEBUG - EntitlementMediator Entitlement Decision is : Permit
    DEBUG - EntitlementMediator User is authorized to perform the action
    DEBUG - EntitlementMediator OnAccept sequence is not defined.
    INFO - SourceHandler Writer null when calling informWriterError
    WARN - SourceHandler Connection time out after request is read: http-incoming-19 Socket Timeout : 60000 Remote Address : /0:0:0:0:0:0:0:1:63398
    WARN - TimeoutHandler Expiring message ID : urn:uuid:045f7259-cc8b-46a7-b9a2-832429163531; dropping message after GLOBAL_TIMEOUT of : 120 seconds for Endpoint

Pasting the message mediation policy file
            <sequence xmlns="http://ws.apache.org/ns/synapse"  name="EM">     <entitlementService xmlns="http://ws.apache.org/ns/synapse" remoteServiceUrl="https://localhost:9443/services" remoteServiceUserName="admin" remoteServicePassword="admin" callbackClass="org.wso2.sample.handlers.entitlement.APIEntitlementCallbackHandler">
                                            <onReject>
                                                            <makefault version="soap12">
                                                                            <code xmlns:soap12Env="http://www.w3.org/2003/05/soap-envelope"
                                                                                value="soap12Env:Receiver"/>
                                                                            <reason value="UNAUTHORIZED"/>
                                                                            <node/>
                                                                            <role/>
                                                                            <detail>XACML Authorization Failed</detail>
                                                            </makefault>
                                                            <respond/>
                                            </onReject>
                                            <onAccept>
                                            <log level="trace" xmlns="http://ws.apache.org/ns/synapse"/>
                                                            <send>
                                                                            <endpoint>
                                                                                <address uri="http://localhost:8080"/>
                                                                            </endpoint>
                                                            </send>
                                            </onAccept>
                                            <obligations/>
                                            <advice/>
                            </entitlementService>
            </sequence>

If I just use respond in OnAccept, instead of send, the call returns immediately, but my back end API doesn't get called.
Am I missing something here ?
Thanks,  Albie Morken

A: It looks like this

*

*is not an issue with XACML but rather with the API manager

*you did not define a happy path for when the PDP replies Permit. You can see that from     DEBUG - EntitlementMediator OnAccept sequence is not defined.
Try defining that path


text:
Q: Can you create resources inside an Azure AD B2C directory? Hierarchy / Relationships
I'm rather confused about the relationship between Azure AD, subscriptions, resources and Azure AD B2C.
This is how I think it's tied together:

*

*An Azure AD directory (or organization?) can have many subscriptions

*Subscriptions can only be tied to a single directory

*Resources (inside resource groups) can only belong to a single subscription

*You can have up to 20 Azure AD B2C tenants/directories per subscription

This gives the following example hierarchy:

*

*Azure AD directory (contoso.com)

*

*Dev subscription

*

*Resource group X

*

*Azure AD B2C #1

*Azure AD B2C #2

*Prod subscription

*

*Resource Group Y

*

*Azure AD B2C #3

*Azure AD B2C #4

Do correct me if I'm wrong, please!
The really confusing part
In the Azure portal, I have a B2C tenant resource in my AD directory:

Also, from the menu in the top right corner, I can click 'Switch directory', and see both my AD directory and my B2C directory:

When I switch to the B2C directory, I get the same left menu that I have in my AD directory:

Ok.
So I have a menu option to create a resource, and I can also view resources inside this B2C directory!
Questions:

*

*Can you actually create resources inside a B2C directory? Seems to me that B2C is itself a resource, belonging to a specific subscription and a specific AD directory.

*If you can, when would you – if ever – do it?

I'm thinking this is simply a quirk of the Azure Portal. I don't see how you could create a resource inside a B2C directory using e.g. ARM / Bicep / Terraform.

A: You cannot create resources in B2C tenant. In general resources are created and belong to the subscription, not the tenant. You would have to have the subscription assigned to your B2C tenant but that is not possible.

*

*Yes it is a resource, belonging to specific subscription (for billing purposes) and subscription is linked to AAD tenant

*No, the main goal of B2C is to manage identities. If it would be ever possible it wouldn't work well. Much better idea is to create an additional subscription in your base tenant if you ever need to separate resources (for example for billing purposes).


text:
Q: How to execute a rails command with sweet alert 2? I have the following sweet alert 2 message:
<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        Swal.fire("Saved!", "", "success");
      } else if (result.isDenied) {
        Swal.fire("Changes are not saved!", "", "info");
      }
    });
'>SHOW SWEET ALERT</button>

The design looks to work okay, but the issue is that I cannot execute an .erb command instead of showing another sweet alert message!
So for example if I change the above code to the following it will mess everything up and I don't know what is causing this!:
<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        <%= link_to "Home Page", root_path, class:"navbar-brand" %>
      } else if (result.isDenied) {
        <%= link_to "About Page", home_about_path, class:"nav-link" %>
      }
    });
'>SHOW SWEET ALERT</button>

CODE SNIPPET 2 WILL GIVE THE FOLLOWING ERROR: Uncaught SyntaxError: Unexpected token '<'
Image example of first snippet:
Image example of second snippet:

A: Actually that is the expected behaviour.
As you can see in the second screenshot, the ERB parser has generated the correct anchor tags inside your JavaScript code causing the SyntaxError. (You can't have HTML in JavaScript! Unless they are around string quote marks of course.)
What you want to do is this instead:
<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        location.pathname = "<%= root_path %>"
      } else if (result.isDenied) {
        location.pathname = "<%= home_about_path %>"
      }
    });
'>SHOW SWEET ALERT</button>

"location.pathname = x" will direct you to a relative path.
The server's ERB parser will replace root_path and home_about_path variables with the paths you're looking for.


text:
Q: Destructors of builtin types (int, char etc..) In C++ the following code gives a compiler error:
void destruct1 (int * item)
{
  item->~int();
}

This code is nearly the same, I just typedef the int to another type and something magic happens:
typedef int myint;

void destruct2 (myint * item)
{
  item->~myint();
}

Why does the second code work? Does an int get a destructor just because it has been typedefed?
In case you wonder why one ever would like to do this: This comes from refactoring C++ code. We're removing the standard heap and replacing it with selfmade pools. This requires us to call placement-new and the destructors. I know that calling destructors for primitive types is useless, but we want them in the code nevertheless in case we later replace PODs with real classes.
Finding out that naked int's don't work but typedefed ones do was quite a surprise.
Btw - I have a solution that involves template-functions. We just typedef inside the template and everything is fine.

A: It's the reason that makes your code work for generic parameters. Consider a container C:
template<typename T>
struct C {
    // ...
    ~C() {
        for(size_t i = 0; i<elements; i++)
            buffer[i].~T();
    }
};

It would be annoying to introduce special cases for built-in types. So C++ allows you to do the above, even if T happens to equal to int. The holy Standard says in 12.4 p15:

The notation for explicit call of a destructor can be used for any scalar type name. Allowing this makes it possible to write code without having to know if a destructor exists for a given type.

The difference between using a plain int and a typedef'ed int is that they are syntactically different things. The rule is, that in a destructor call, the thing after the ~ is a type-name. int is not such a thing, but a typedef-name is. Look it up in 7.1.5.2.


text:
Q: AutoProperties doesn't work with DelegateCommand.ObservesCanExecute in prism? There is something under the hood that I don't understand with ObservesCanExecute on DelegateCommand in prism.
It has something to see with AutoProperties ... I think
I have a View with a button which is bound to a DelegateCommand in my viewmodel.
For some reasons, in my view, I catch the the CanExecuteChanged event like this :
MyButton.Command.CanExecuteChanged += Command_CanExecuteChanged;

The question is, in my viewmodel, when I use autoproperties to declare IsEnabled, the event in the view is not fired. It is like if ObservesCanExecute doesn't work anymore. Is it normal ? Is there something I'm doing wrong ? I thought that AutoProperties and Properties were exactly the same ...
Here is my ViewModel :
public class MainPageViewModel : ViewModelBase
{
    // VERSION 1 - It Works
    private bool _isEnabled = true;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set { SetProperty(ref _isEnabled, value); }
    }

    // VERSION 2 - Don't works
    // public bool IsEnabled {get; set; } = true;

    public DelegateCommand MyCommand { get; set; } = null;

    public MainPageViewModel(INavigationService navigationService)
        : base(navigationService)
    {
        Title = "Main Page";
        MyCommand = new DelegateCommand(Execute).ObservesCanExecute(() => IsEnabled);
    }

    private void Execute()
    {
        IsEnabled = !IsEnabled;
    }
}

A: ObservesCanExecuteChanged relies on INotifyPropertyChanged of the class containing the observed property.
This raises the event in case of a change and thus works
private bool _isEnabled = true;
public bool IsEnabled
{
    get { return _isEnabled; }
    set { SetProperty(ref _isEnabled, value); }
}

while this raises no event and does not work, as you observed:
public bool IsEnabled { get; set; }

I thought that AutoProperties and Properties were exactly the same

That's just plain wrong. An "AutoProperty" is a "Property", but that's it concerning the similarities. They may look alike from the outside of a class, but a property can just do anything, while an auto property is just a overly complicated field.


text:
Q: Avoiding the N+1 issue in a nested object? I am experiencing inefficient Hibernate queries, and I believe the cause to be the so-called  N+1 problem that I've read about elsewhere. However, I am not sure how to solve the problem, since my objects are nested, and most example solutions I've seen online are trivial.
Here's a brief description of my application.
I have an ExecutionTrace class, which has a one-to-many relationship with the TraceLine class. TraceLine in turn has a one-to-many relationship with the TraceReference class. Each of these classes has an id attribute, generated by Hibernate. (All the classes contain a few member variables, but I'll omit those for now.)
In my application, I'm querying for a particular ExecutionTrace, and then my application will iterate through all of it's TraceLine objects and their TraceReference objects. Thus, I've set the LazyCollectionOption to false for all of these relationships:
// ExecutionTrace.java:
...
@Id @GeneratedValue
@Column(name = "file_id")
public long id;
...
@OneToMany(mappedBy = "container_trace_", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@OrderBy(clause = "id")
public List<TraceLine> lines_ = new ArrayList<TraceLine>();
...

// TraceLine.java:
...
@Id @GeneratedValue
@Column(name = "trace_line_id")
@Index(name = "traceIDIndex")
public long id;
...
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "file_id")
@LazyCollection(LazyCollectionOption.TRUE)
public ExecutionTrace container_trace_;
...
@OneToMany(mappedBy = "trace_line_", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@OrderBy(clause = "id")
public List<TraceReference> trace_references_ = new ArrayList<TraceReference>();
...

// TraceReference.java:
...
@Id @GeneratedValue
@Column(name = "trace_reference_id")
@Index(name="TraceReferenceIDIndex")
public long id;
...
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "trace_line_id")
@LazyCollection(LazyCollectionOption.TRUE)
public TraceLine trace_line_;
...

My hibernate query to select an ExecutionTrace is:
String f_hash = ...;

Transaction tx3 = session.beginTransaction();
    String queryString = " from ExecutionTrace where hash_ = '"+ f_hash +"'";

List<ExecutionTrace> res2 = session.createQuery(queryString).list();
tx3.commit();

In one of my simple test cases, there's 1 ExecutionTrace object, which contains 645 TraceLine objects, each containing between 1 and 5 TraceReference objects. The query, and the code to iterate through all of them, is taking 50+ seconds on modest hardware. The database, PostgreSQL, is running on the same machine as the application.
Looking at the SQL queries thrown by Hibernate, I noticed that:

*

*There is 1 query to select all the TraceLine objects. This is good.

*There are 645 queries to select TraceReference objects. This is bad. Plus, they all have a lot of outer joins going on, making them inefficient.

For example, here's a query to TraceReference:
    select
        trace_refe0_.trace_line_id as trace5_6_18_,
        trace_refe0_.trace_reference_id as trace1_18_,
        trace_refe0_.trace_reference_id as trace1_7_17_,
        trace_refe0_.new_value as new2_7_17_,
        trace_refe0_.old_value as old3_7_17_,
        trace_refe0_.operand_id as operand4_7_17_,
        trace_refe0_.trace_line_id as trace5_7_17_,
        operand1_.operand_id as operand1_11_0_,
        operand1_.operand_index as operand2_11_0_,
        operand1_.is_dest as is3_11_0_,
        operand1_.is_source as is4_11_0_,
        operand1_.operand_size as operand5_11_0_,
        operand1_.operand_u_prop_id as operand6_11_0_,
        operand1_.maps_to_variable as maps7_11_0_,
        operandtyp2_.operand_prop_id as operand2_12_1_,
        operandtyp2_1_.constant_value as constant1_13_1_,
        operandtyp2_2_.register_name as register1_14_1_,
        operandtyp2_4_.base_operand_id as base2_16_1_,
        operandtyp2_4_.displacement_operand_id as displace3_16_1_,
        operandtyp2_4_.index_operand_id as index4_16_1_,
        operandtyp2_4_.ml_name as ml1_16_1_,
        operandtyp2_4_.scale_operand_id as scale5_16_1_,
        operandtyp2_.DTYPE as DTYPE12_1_,
        register3_.operand_prop_id as operand2_12_2_,
        register3_1_.register_name as register1_14_2_,
        constant4_.operand_prop_id as operand2_12_3_,
        constant4_1_.constant_value as constant1_13_3_,
        register5_.operand_prop_id as operand2_12_4_,
        register5_1_.register_name as register1_14_4_,
        constant6_.operand_prop_id as operand2_12_5_,
        constant6_1_.constant_value as constant1_13_5_,
        variable7_.variable_id as variable1_18_6_,
        variable7_.file_id as file6_18_6_,
        variable7_.function_id as function7_18_6_,
        variable7_.variable_is_argument as variable2_18_6_,
        variable7_.variable_is_global as variable3_18_6_,
        variable7_.variable_is_static as variable4_18_6_,
        variable7_.variable_name as variable5_18_6_,
        variable7_.data_type_id as data8_18_6_,
        sourcefile8_.file_id as file2_0_7_,
        sourcefile8_.file_path as file3_0_7_,
        sourcefile8_.file_name as file4_0_7_,
        sourcefile8_.source_lang as source5_0_7_,
        function9_.function_id as function1_8_8_,
        function9_.file_id as file6_8_8_,
        function9_.function_end_address as function2_8_8_,
        function9_.function_address as function3_8_8_,
        function9_.function_name as function4_8_8_,
        function9_.function_is_static as function5_8_8_,
        sourcefile10_.file_id as file2_0_9_,
        sourcefile10_.file_path as file3_0_9_,
        sourcefile10_.file_name as file4_0_9_,
        sourcefile10_.source_lang as source5_0_9_,
        datatype11_.data_type_id as data2_19_10_,
        datatype11_.defined_by as defined5_19_10_,
        datatype11_.data_type_length as data3_19_10_,
        datatype11_.data_type_name as data4_19_10_,
        datatype11_2_.pointer_to as pointer1_20_10_,
        datatype11_3_.array_size as array1_21_10_,
        datatype11_3_.contains_type as contains2_21_10_,
        datatype11_4_.enumerator_count as enumerator1_22_10_,
        datatype11_5_.type_ as type1_24_10_,
        datatype11_6_.constant_of_type as constant1_25_10_,
        datatype11_7_.return_type as return1_27_10_,
        datatype11_.DTYPE as DTYPE19_10_,
        sourcefile12_.file_id as file2_0_11_,
        sourcefile12_.file_path as file3_0_11_,
        sourcefile12_.file_name as file4_0_11_,
        sourcefile12_.source_lang as source5_0_11_,
        datatype13_.data_type_id as data2_19_12_,
        datatype13_.defined_by as defined5_19_12_,
        datatype13_.data_type_length as data3_19_12_,
        datatype13_.data_type_name as data4_19_12_,
        datatype13_2_.pointer_to as pointer1_20_12_,
        datatype13_3_.array_size as array1_21_12_,
        datatype13_3_.contains_type as contains2_21_12_,
        datatype13_4_.enumerator_count as enumerator1_22_12_,
        datatype13_5_.type_ as type1_24_12_,
        datatype13_6_.constant_of_type as constant1_25_12_,
        datatype13_7_.return_type as return1_27_12_,
        datatype13_.DTYPE as DTYPE19_12_,
        datatype14_.data_type_id as data2_19_13_,
        datatype14_.defined_by as defined5_19_13_,
        datatype14_.data_type_length as data3_19_13_,
        datatype14_.data_type_name as data4_19_13_,
        datatype14_2_.pointer_to as pointer1_20_13_,
        datatype14_3_.array_size as array1_21_13_,
        datatype14_3_.contains_type as contains2_21_13_,
        datatype14_4_.enumerator_count as enumerator1_22_13_,
        datatype14_5_.type_ as type1_24_13_,
        datatype14_6_.constant_of_type as constant1_25_13_,
        datatype14_7_.return_type as return1_27_13_,
        datatype14_.DTYPE as DTYPE19_13_,
        datatype15_.data_type_id as data2_19_14_,
        datatype15_.defined_by as defined5_19_14_,
        datatype15_.data_type_length as data3_19_14_,
        datatype15_.data_type_name as data4_19_14_,
        datatype15_2_.pointer_to as pointer1_20_14_,
        datatype15_3_.array_size as array1_21_14_,
        datatype15_3_.contains_type as contains2_21_14_,
        datatype15_4_.enumerator_count as enumerator1_22_14_,
        datatype15_5_.type_ as type1_24_14_,
        datatype15_6_.constant_of_type as constant1_25_14_,
        datatype15_7_.return_type as return1_27_14_,
        datatype15_.DTYPE as DTYPE19_14_,
        datatype16_.data_type_id as data2_19_15_,
        datatype16_.defined_by as defined5_19_15_,
        datatype16_.data_type_length as data3_19_15_,
        datatype16_.data_type_name as data4_19_15_,
        datatype16_2_.pointer_to as pointer1_20_15_,
        datatype16_3_.array_size as array1_21_15_,
        datatype16_3_.contains_type as contains2_21_15_,
        datatype16_4_.enumerator_count as enumerator1_22_15_,
        datatype16_5_.type_ as type1_24_15_,
        datatype16_6_.constant_of_type as constant1_25_15_,
        datatype16_7_.return_type as return1_27_15_,
        datatype16_.DTYPE as DTYPE19_15_,
        datatype17_.data_type_id as data2_19_16_,
        datatype17_.defined_by as defined5_19_16_,
        datatype17_.data_type_length as data3_19_16_,
        datatype17_.data_type_name as data4_19_16_,
        datatype17_2_.pointer_to as pointer1_20_16_,
        datatype17_3_.array_size as array1_21_16_,
        datatype17_3_.contains_type as contains2_21_16_,
        datatype17_4_.enumerator_count as enumerator1_22_16_,
        datatype17_5_.type_ as type1_24_16_,
        datatype17_6_.constant_of_type as constant1_25_16_,
        datatype17_7_.return_type as return1_27_16_,
        datatype17_.DTYPE as DTYPE19_16_
    from
        TraceReference trace_refe0_
    left outer join
        Operand operand1_
            on trace_refe0_.operand_id=operand1_.operand_id
    left outer join
        OperandProperties operandtyp2_
            on operand1_.operand_u_prop_id=operandtyp2_.operand_prop_id
    left outer join
        Constant operandtyp2_1_
            on operandtyp2_.operand_prop_id=operandtyp2_1_.operand_prop_id
    left outer join
        Register operandtyp2_2_
            on operandtyp2_.operand_prop_id=operandtyp2_2_.operand_prop_id
    left outer join
        UnknownOperandProperties operandtyp2_3_
            on operandtyp2_.operand_prop_id=operandtyp2_3_.operand_prop_id
    left outer join
        MemoryLocation operandtyp2_4_
            on operandtyp2_.operand_prop_id=operandtyp2_4_.operand_prop_id
    left outer join
        OperandProperties register3_
            on operandtyp2_4_.base_operand_id=register3_.operand_prop_id
    left outer join
        Register register3_1_
            on register3_.operand_prop_id=register3_1_.operand_prop_id
    left outer join
        OperandProperties constant4_
            on operandtyp2_4_.displacement_operand_id=constant4_.operand_prop_id
    left outer join
        Constant constant4_1_
            on constant4_.operand_prop_id=constant4_1_.operand_prop_id
    left outer join
        OperandProperties register5_
            on operandtyp2_4_.index_operand_id=register5_.operand_prop_id
    left outer join
        Register register5_1_
            on register5_.operand_prop_id=register5_1_.operand_prop_id
    left outer join
        OperandProperties constant6_
            on operandtyp2_4_.scale_operand_id=constant6_.operand_prop_id
    left outer join
        Constant constant6_1_
            on constant6_.operand_prop_id=constant6_1_.operand_prop_id
    left outer join
        Variable variable7_
            on operand1_.maps_to_variable=variable7_.variable_id
    left outer join
        FileOnDisk sourcefile8_
            on variable7_.file_id=sourcefile8_.file_id
    left outer join
        ObjectFile sourcefile8_1_
            on sourcefile8_.file_id=sourcefile8_1_.file_id
    left outer join
        SourceFile sourcefile8_2_
            on sourcefile8_.file_id=sourcefile8_2_.file_id
    left outer join
        SourceFunction function9_
            on variable7_.function_id=function9_.function_id
    left outer join
        FileOnDisk sourcefile10_
            on function9_.file_id=sourcefile10_.file_id
    left outer join
        ObjectFile sourcefile10_1_
            on sourcefile10_.file_id=sourcefile10_1_.file_id
    left outer join
        SourceFile sourcefile10_2_
            on sourcefile10_.file_id=sourcefile10_2_.file_id
    left outer join
        DataType datatype11_
            on variable7_.data_type_id=datatype11_.data_type_id
    left outer join
        Pointer datatype11_1_
            on datatype11_.data_type_id=datatype11_1_.data_type_id
    left outer join
        Pointer datatype11_2_
            on datatype11_.data_type_id=datatype11_2_.data_type_id
    left outer join
        SourceArray datatype11_3_
            on datatype11_.data_type_id=datatype11_3_.data_type_id
    left outer join
        Enum datatype11_4_
            on datatype11_.data_type_id=datatype11_4_.data_type_id
    left outer join
        Typedef datatype11_5_
            on datatype11_.data_type_id=datatype11_5_.data_type_id
    left outer join
        ConstantType datatype11_6_
            on datatype11_.data_type_id=datatype11_6_.data_type_id
    left outer join
        FunctionType datatype11_7_
            on datatype11_.data_type_id=datatype11_7_.data_type_id
    left outer join
        FileOnDisk sourcefile12_
            on datatype11_.defined_by=sourcefile12_.file_id
    left outer join
        ObjectFile sourcefile12_1_
            on sourcefile12_.file_id=sourcefile12_1_.file_id
    left outer join
        SourceFile sourcefile12_2_
            on sourcefile12_.file_id=sourcefile12_2_.file_id
    left outer join
        DataType datatype13_
            on datatype11_2_.pointer_to=datatype13_.data_type_id
    left outer join
        Pointer datatype13_1_
            on datatype13_.data_type_id=datatype13_1_.data_type_id
    left outer join
        Pointer datatype13_2_
            on datatype13_.data_type_id=datatype13_2_.data_type_id
    left outer join
        SourceArray datatype13_3_
            on datatype13_.data_type_id=datatype13_3_.data_type_id
    left outer join
        Enum datatype13_4_
            on datatype13_.data_type_id=datatype13_4_.data_type_id
    left outer join
        Typedef datatype13_5_
            on datatype13_.data_type_id=datatype13_5_.data_type_id
    left outer join
        ConstantType datatype13_6_
            on datatype13_.data_type_id=datatype13_6_.data_type_id
    left outer join
        FunctionType datatype13_7_
            on datatype13_.data_type_id=datatype13_7_.data_type_id
    left outer join
        DataType datatype14_
            on datatype13_3_.contains_type=datatype14_.data_type_id
    left outer join
        Pointer datatype14_1_
            on datatype14_.data_type_id=datatype14_1_.data_type_id
    left outer join
        Pointer datatype14_2_
            on datatype14_.data_type_id=datatype14_2_.data_type_id
    left outer join
        SourceArray datatype14_3_
            on datatype14_.data_type_id=datatype14_3_.data_type_id
    left outer join
        Enum datatype14_4_
            on datatype14_.data_type_id=datatype14_4_.data_type_id
    left outer join
        Typedef datatype14_5_
            on datatype14_.data_type_id=datatype14_5_.data_type_id
    left outer join
        ConstantType datatype14_6_
            on datatype14_.data_type_id=datatype14_6_.data_type_id
    left outer join
        FunctionType datatype14_7_
            on datatype14_.data_type_id=datatype14_7_.data_type_id
    left outer join
        DataType datatype15_
            on datatype14_5_.type_=datatype15_.data_type_id
    left outer join
        Pointer datatype15_1_
            on datatype15_.data_type_id=datatype15_1_.data_type_id
    left outer join
        Pointer datatype15_2_
            on datatype15_.data_type_id=datatype15_2_.data_type_id
    left outer join
        SourceArray datatype15_3_
            on datatype15_.data_type_id=datatype15_3_.data_type_id
    left outer join
        Enum datatype15_4_
            on datatype15_.data_type_id=datatype15_4_.data_type_id
    left outer join
        Typedef datatype15_5_
            on datatype15_.data_type_id=datatype15_5_.data_type_id
    left outer join
        ConstantType datatype15_6_
            on datatype15_.data_type_id=datatype15_6_.data_type_id
    left outer join
        FunctionType datatype15_7_
            on datatype15_.data_type_id=datatype15_7_.data_type_id
    left outer join
        DataType datatype16_
            on datatype15_6_.constant_of_type=datatype16_.data_type_id
    left outer join
        Pointer datatype16_1_
            on datatype16_.data_type_id=datatype16_1_.data_type_id
    left outer join
        Pointer datatype16_2_
            on datatype16_.data_type_id=datatype16_2_.data_type_id
    left outer join
        SourceArray datatype16_3_
            on datatype16_.data_type_id=datatype16_3_.data_type_id
    left outer join
        Enum datatype16_4_
            on datatype16_.data_type_id=datatype16_4_.data_type_id
    left outer join
        Typedef datatype16_5_
            on datatype16_.data_type_id=datatype16_5_.data_type_id
    left outer join
        ConstantType datatype16_6_
            on datatype16_.data_type_id=datatype16_6_.data_type_id
    left outer join
        FunctionType datatype16_7_
            on datatype16_.data_type_id=datatype16_7_.data_type_id
    left outer join
        DataType datatype17_
            on datatype16_7_.return_type=datatype17_.data_type_id
    left outer join
        Pointer datatype17_1_
            on datatype17_.data_type_id=datatype17_1_.data_type_id
    left outer join
        Pointer datatype17_2_
            on datatype17_.data_type_id=datatype17_2_.data_type_id
    left outer join
        SourceArray datatype17_3_
            on datatype17_.data_type_id=datatype17_3_.data_type_id
    left outer join
        Enum datatype17_4_
            on datatype17_.data_type_id=datatype17_4_.data_type_id
    left outer join
        Typedef datatype17_5_
            on datatype17_.data_type_id=datatype17_5_.data_type_id
    left outer join
        ConstantType datatype17_6_
            on datatype17_.data_type_id=datatype17_6_.data_type_id
    left outer join
        FunctionType datatype17_7_
            on datatype17_.data_type_id=datatype17_7_.data_type_id
    where
        trace_refe0_.trace_line_id=?
    order by
        trace_refe0_.trace_reference_id
TRACE [main] 06/26/13 10:00:54 preparing statement
TRACE [main] 06/26/13 10:00:54 binding parameter [1] as [BIGINT] - 82883

I tried modifying my query so that it performed some inner joins:
    String queryString =    " from ExecutionTrace as et " +
               "inner join fetch et.lines_ as lines " +
        "where et.hash_ = '"+ f_hash +"'";

This resulted in 0 queries to select TraceLines, and 645 queries to select TraceReferences. No help. I then tried multiple inner joins:
    String queryString =
    " from ExecutionTrace as et " +
       "inner join fetch et.lines_ as lines " +
       "inner join fetch lines.trace_references_ " +
    "where et.hash_ = '"+ f_hash +"'";

This resulted in an exception:
Exception in thread "main" org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags.

I feel I'm close to solving the problem, but just missing something easy.

A: After doing some research and experimentation, I've found two possible solutions to this problem, each with their own pros and cons.
1. Use SUBSELECT Fetch Mode
Use the @Fetch annotation to cause Hibernate to product a sub-select query:
@OneToMany(mappedBy = "container_trace_", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.TRUE)
@OrderBy(clause = "id")
@Fetch(FetchMode.SUBSELECT)
public List<TraceLine> lines_ = new ArrayList<TraceLine>();

*

*Pro: The above annotation will cause all the TraceLine objects to be fetched at the same time (i.e., in the same select statement) as the ExecutionTrace, resulting in far fewer select statements.

*Con: If the ExecutionTrace has a lot of TraceLine objects, the sub select will cause your JVM to run out of memory.

2. Use Batches
If you have too many TraceLine objects to fit into memory, and hence you can't use SUBSELECT as described above, you have another option. Use the @BatchSize annotation to cause Hibernate to fetch 10 TraceLine objects at a time, instead of just one.
@OneToMany(mappedBy = "container_trace_", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.TRUE)
@OrderBy(clause = "id")
@BatchSize(size = 10)
public List<TraceLine> lines_ = new ArrayList<TraceLine>();

*

*Pro: This effectively reduces the the number of selects by a factor of 10

*Pro: Won't run out of memory

*Con: Still will be a large number of selects, if the number of TraceLine objects is large.

Neither solution is perfect. In my application, I went with batches.


text:
Q: MongoDB: queue vs. realtime write/update On a large mongoDB I have 2 different use-cases for reading and 2 different types for write/update.

*

*read 1: find by index -> no question on this. this works like a charm - as long as the index fits in the memory/ram.

*read 2: read line by line, like a batch script which is reading a log-file one by one.

*write 1: insert - append a new dataset or document.

*write 2: update data, directly addresses or found by index.

Now I wonder if mongoDB is able to "priorize" different write-tasks. I have one collection which does not require the data to be written and available instantly in "real-time". It's enough to use a slow queque and process these writing tasks without hurry.
However, there are also write statements that should be processed asap and be available with a minimum delay (if any).
Does mongoDB allow me to differ between high (asap) and low prio (queque) writing/updating?

A: There is no priority system currently for writes (or reads, though you can send reads to secondaries) - the closest thing you will get is yielding.  For long running operations and for operations that it predicts will page in data from disk, MongoDB will yield the lock and allow other operations through, essentially interleaving operations:
If you wanted to make sure that the less important writes are throttled somewhat you could rate limit them by ensuring they are replicated W=2, REPLICAS_SAFE, or similar writes (depending on your driver).  See here for the command behind such implementations on the MongoDB side - take a look at your driver docs for the relevant equivalent there.
http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-%7B%7Bw%7D%7D
There would then be a slight delay as the write waits for replication out to the secondaries, allowing your other, more important writes their shot at the write lock.
http://www.mongodb.org/display/DOCS/How+does+concurrency+work
In terms of the future, with 2.2 due out shortly, you will get database level locking, so as long as your 2 different profiles/priorities are in different databases you should have no lock contention (IO/RAM contention may still exist, of course).
Finally, in terms of other things to look at, for the line by line type read, I would look at capped collections and tailable cursors - see if they fit your use case:
http://www.mongodb.org/display/DOCS/Tailable+Cursors