structure as input instead of string in kafka producer using librdkafka

Question: I need to take input as structure instead of string in producer and print that in consumer using librdkafka library.I made changes in the producer code and even able to get the structure, but in the consumer it is not showing plz help if there need some more changes
Here is the code
producer code:
<code>struct date
{
int d, m, y;
};

int main(int argc, char** argv) {
rd_kafka_t* rk;         /* Producer instance handle */
rd_kafka_conf_t* conf;  /* Temporary configuration object */
char errstr[512];       /* librdkafka API error reporting buffer */
//char buf[512];          /* Message value temporary buffer */
const char* brokers;    /* Argument: broker list */
const char* topic;      /* Argument: topic to produce to */
struct date  d1;
struct date* ptr ;
ptr = &d1;
int i;

brokers ="localhost:9092";
topic = "test";

/*
 * Create Kafka client configuration place-holder
 */
conf = rd_kafka_conf_new();

/* Set bootstrap broker(s) as a comma-separated list of
 * host or host:port (default port 9092).
 * librdkafka will use the bootstrap brokers to acquire the full
 * set of brokers from the cluster. */
if (rd_kafka_conf_set(conf, "bootstrap.servers", brokers,
    errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {
    fprintf(stderr, "%s\n", errstr);
    return 1;
}

/* Set the delivery report callback.
 * This callback will be called once per message to inform
 * the application if delivery succeeded or failed.
 * See dr_msg_cb() above.
 * The callback is only triggered from rd_kafka_poll() and
 * rd_kafka_flush(). */
rd_kafka_conf_set_dr_msg_cb(conf, dr_msg_cb);

/*
 * Create producer instance.
 *
 * NOTE: rd_kafka_new() takes ownership of the conf object
 *       and the application must not reference it again after
 *       this call.
 */
rk = rd_kafka_new(RD_KAFKA_PRODUCER, conf, errstr, sizeof(errstr));
if (!rk) {
    fprintf(stderr,
        "%% Failed to create new producer: %s\n", errstr);
    return 1;
}

/* Signal handler for clean shutdown */
signal(SIGINT, stop);

fprintf(stderr, "%% enter \n");
/*fprintf(stderr,
    "%% Type some text and hit enter to produce message\n"
    "%% Or just hit enter to only serve delivery reports\n"
    "%% Press Ctrl-C or Ctrl-D to exit\n");*/

while (run && fscanf_s(stdin, "%d/%d/%d", &d1.d, &d1.m,&d1.y))
{

    size_t len = sizeof(d1);
    rd_kafka_resp_err_t err;
    fprintf(stdout, "%d/%d/%d \n", d1.d, d1.m, d1.y);

    //if ([len - 1] == '\n') /* Remove newline */
       // d1[--len] = '\0';

    if (len == 0) {
        /* Empty line: only serve delivery reports */
        rd_kafka_poll(rk, 0/*non-blocking */);
        continue;
    }

retry:
    err = rd_kafka_producev(
        /* Producer handle */
        rk,
        /* Topic name */
        RD_KAFKA_V_TOPIC(topic),
        /* Make a copy of the payload. */
        RD_KAFKA_V_MSGFLAGS(RD_KAFKA_MSG_F_COPY),
        /* Message value and length */
        RD_KAFKA_V_VALUE(ptr, len),
        /* Per-Message opaque, provided in
         * delivery report callback as
         * msg_opaque. */
        RD_KAFKA_V_OPAQUE(NULL),
        /* End sentinel */
        RD_KAFKA_V_END);

    if (err) {
        /*
         * Failed to *enqueue* message for producing.
         */
        fprintf(stderr,
            "%% Failed to produce to topic %s: %s\n",
            topic, rd_kafka_err2str(err));

        if (err == RD_KAFKA_RESP_ERR__QUEUE_FULL) {
            /* If the internal queue is full, wait for
             * messages to be delivered and then retry.
             * The internal queue represents both
             * messages to be sent and messages that have
             * been sent or failed, awaiting their
             * delivery report callback to be called.
             *
             * The internal queue is limited by the
             * configuration property
             * queue.buffering.max.messages */
            rd_kafka_poll(rk, 1000/*block for max 1000ms*/);
            goto retry;
        }
    }
    else {
        fprintf(stderr, "%% Enqueued message (%zd bytes) "
            "for topic %s\n",
            len, topic);
    }

    /* A producer application should continually serve
     * the delivery report queue by calling rd_kafka_poll()
     * at frequent intervals.
     * Either put the poll call in your main loop, or in a
     * dedicated thread, or call it after every
     * rd_kafka_produce() call.
     * Just make sure that rd_kafka_poll() is still called
     * during periods where you are not producing any messages
     * to make sure previously produced messages have their
     * delivery report callback served (and any other callbacks
     * you register). */
    rd_kafka_poll(rk, 0/*non-blocking*/);
}

/* Wait for final messages to be delivered or fail.
 * rd_kafka_flush() is an abstraction over rd_kafka_poll() which
 * waits for all messages to be delivered. */
fprintf(stderr, "%% Flushing final messages..\n");
rd_kafka_flush(rk, 10 * 1000 /* wait for max 10 seconds */);

/* If the output queue is still not empty there is an issue
 * with producing messages to the clusters. */
if (rd_kafka_outq_len(rk) > 0)
    fprintf(stderr, "%% %d message(s) were not delivered\n",
        rd_kafka_outq_len(rk));

/* Destroy the producer instance */
rd_kafka_destroy(rk);

return 0;
}
</code>
consumer code:
<code>#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <ctype.h>

/* Typical include path would be <librdkafka/rdkafka.h>, but this program
* is builtin from within the librdkafka source tree and thus differs. */
//#include <librdkafka/rdkafka.h>
#include "rdkafka.h"

static volatile sig_atomic_t run = 1;

/**
* @brief Signal termination of program
*/
static void stop(int sig) {
run = 0;
}

struct date
{
int d, m, y;
};

/**
* @returns 1 if all bytes are printable, else 0.
*/
static int is_printable(struct date* ptr, size_t len)
{
size_t i;

for (i = 0; i < len; i++)
    if (!isdigit(d1.d && d1.m && d1.y))
        return 0;

return 1;
}

int main(int argc, char **argv) {
rd_kafka_t* rk;          /* Consumer instance handle */
rd_kafka_conf_t* conf;   /* Temporary configuration object */
rd_kafka_resp_err_t err; /* librdkafka API error code */
char errstr[512];        /* librdkafka API error reporting buffer */
const char* brokers;     /* Argument: broker list */
const char* groupid;     /* Argument: Consumer group id */
char** topics;           /* Argument: list of topics to subscribe to */
int topic_cnt;           /* Number of topics to subscribe to */
rd_kafka_topic_partition_list_t* subscription; /* Subscribed topics */
int i;
struct date  d1;
struct date* ptr;
ptr = &d1;

/*
 * Argument validation
 */
 /*if (argc < 4) {
     fprintf(stderr,
         "%% Usage: "
         "%s <broker> <group.id> <topic1> <topic2>..\n",
         argv[0]);
     return 1;
 }*/

brokers = "localhost:9092";
groupid = "test-consumer-group";
char* topic[] = {"test"};
topics = &topic;
topic_cnt = 1;

/*
 * Create Kafka client configuration place-holder
 */
conf = rd_kafka_conf_new();

/* Set bootstrap broker(s) as a comma-separated list of
 * host or host:port (default port 9092).
 * librdkafka will use the bootstrap brokers to acquire the full
 * set of brokers from the cluster. */
if (rd_kafka_conf_set(conf, "bootstrap.servers", brokers,
    errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {
    fprintf(stderr, "%s\n", errstr);
    rd_kafka_conf_destroy(conf);
    return 1;
}

/* Set the consumer group id.
 * All consumers sharing the same group id will join the same
 * group, and the subscribed topic' partitions will be assigned
 * according to the partition.assignment.strategy
 * (consumer config property) to the consumers in the group. */
if (rd_kafka_conf_set(conf, "group.id", groupid,
    errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {
    fprintf(stderr, "%s\n", errstr);
    rd_kafka_conf_destroy(conf);
    return 1;
}

/* If there is no previously committed offset for a partition
 * the auto.offset.reset strategy will be used to decide where
 * in the partition to start fetching messages.
 * By setting this to earliest the consumer will read all messages
 * in the partition if there was no previously committed offset. */
if (rd_kafka_conf_set(conf, "auto.offset.reset", "earliest",
    errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {
    fprintf(stderr, "%s\n", errstr);
    rd_kafka_conf_destroy(conf);
    return 1;
}

/*
 * Create consumer instance.
 *
 * NOTE: rd_kafka_new() takes ownership of the conf object
 *       and the application must not reference it again after
 *       this call.
 */
rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr, sizeof(errstr));
if (!rk) {
    fprintf(stderr,
        "%% Failed to create new consumer: %s\n", errstr);
    return 1;
}

conf = NULL; /* Configuration object is now owned, and freed,
              * by the rd_kafka_t instance. */

              /* Redirect all messages from per-partition queues to
               * the main queue so that messages can be consumed with one
               * call from all assigned partitions.
               *
               * The alternative is to poll the main queue (for events)
               * and each partition queue separately, which requires setting
               * up a rebalance callback and keeping track of the assignment:
               * but that is more complex and typically not recommended. */
rd_kafka_poll_set_consumer(rk);

/* Convert the list of topics to a format suitable for librdkafka */
subscription = rd_kafka_topic_partition_list_new(topic_cnt);
for (i = 0; i < topic_cnt; i++)
    rd_kafka_topic_partition_list_add(subscription,
        topics[i],
        /* the partition is ignored
         * by subscribe() */
        RD_KAFKA_PARTITION_UA);

/* Subscribe to the list of topics */
err = rd_kafka_subscribe(rk, subscription);
if (err) {
    fprintf(stderr,
        "%% Failed to subscribe to %d topics: %s\n",
        subscription->cnt, rd_kafka_err2str(err));
    rd_kafka_topic_partition_list_destroy(subscription);
    rd_kafka_destroy(rk);
    return 1;
}

fprintf(stderr,
    "%% Subscribed to %d topic(s), "
    "waiting for rebalance and messages...\n",
    subscription->cnt);

rd_kafka_topic_partition_list_destroy(subscription);

/* Signal handler for clean shutdown */
signal(SIGINT, stop);

/* Subscribing to topics will trigger a group rebalance
 * which may take some time to finish, but there is no need
 * for the application to handle this idle period in a special way
 * since a rebalance may happen at any time.
 * Start polling for messages. */

while (run) {
    rd_kafka_message_t* rkm;
    rkm = rd_kafka_consumer_poll(rk, 100);

    if (!rkm)
        continue; /* Timeout: no message within 100ms,
                   *  try again. This short timeout allows
                   *  checking for `run` at frequent intervals.
                   */

                   /* consumer_poll() will return either a proper message
                    * or a consumer error (rkm->err is set). */
    if (rkm->err) {
        /* Consumer errors are generally to be considered
         * informational as the consumer will automatically
         * try to recover from all types of errors. */
        fprintf(stderr,
            "%% Consumer error: %s\n",
            rd_kafka_message_errstr(rkm));
        rd_kafka_message_destroy(rkm);
        continue;
    }

    /* Proper message. */
    printf("Message on %s [%" PRId32 "] at offset %" PRId64 ":\n",
        rd_kafka_topic_name(rkm->rkt), rkm->partition,
        rkm->offset);

    /* Print the message key. */
    if (rkm->key && is_printable((const char*)rkm->key, rkm->key_len))
        printf(" Key: %.*s\n",
            (int)rkm->key_len, (const char*)rkm->key);
    else if (rkm->key)
        printf(" Key: (%d bytes)\n", (int)rkm->key_len);

    /* Print the message value/payload. */
    if (rkm->payload && is_printable((const char*)rkm->payload, rkm->len))
        printf(" Value:%.*s\n",
            (int)rkm->len, (const char*)rkm->payload);
    else if (rkm->payload)
        printf(" Value: (%d bytes)\n", (int)rkm->len);

    rd_kafka_message_destroy(rkm);
}

/* Close the consumer: commit final offsets and leave the group. */
fprintf(stderr, "%% Closing consumer\n");
rd_kafka_consumer_close(rk);

/* Destroy the consumer */
rd_kafka_destroy(rk);

return 0;
}
</code>
Answer: You need to serialize your data before sending it to Kafka.
Recommend using Protobuf, JSON, or Avro.


Question about Maclaurin Series for $\cos x$

Question: I understand how to get the proper maclaurin series representation for $\cos x$, but I'm having trouble understanding the following part conceptually:
I get $\cos x$ as $\sum_{n=0}^\infty (-1)^n\frac{x^{2n}}{2n!}$
but,
Can the maclaurin series of $\cos x$ also be $\sum_{n=0}^\infty (-1)^n\frac{x^n}{n!}$?
I'm confused because even though the odd powers of this functions are going to $0$, wouldn't it still be valid to include them in our maclaurin series? Furthermore, why do we omit terms if they are $0$?
Answer: Maclaurin series are unique when they exists and the second one is $$1-x+\frac{x^2}{2}\mp \dots$$ which is $\exp(-x)$. But
$$\cos(x)=1-\frac{x^2}{2} +\frac{x^4}{4!} \mp \dots$$
For sure we allow terms when they are zero, but here those would it make much more complicate to write it in a closed form, thats why we don't write them.
Answer: The answer to the first question is no.  The latter series is that for $e^{-x}$.  The inclusion of only even terms is a consequence of $\cos{x}$ being an even function.  That said, sure you can include zero terms in a sum, but do you go around saying that $5$ is really $5+0$?  There may be instances where it makes sense to do so, but under normal circumstances, no.


Preservation of angle by multiplication of conjugate

Question: I need help to understand a certain part of a proof (b). I have problems to understand the sentence and its conclusion, "Since B and M' depend continiously on $\beta$ only one of the two values $\pm\alpha$ can occur" why does $B$ and $M'$ depend continiously on $\beta$ and why does it follow that either $\alpha$ or $-\alpha$?
Source Algebra Artin 2nd edition page 137/138
Answer: To elaborate on Artin's phrasing of the argument:
Let $B$ be a rotation about some pole $p$, and let $B$ have rotation angle $\beta$. Fix $p$ and let $\beta$ vary. Each entry of the matrix $B$ is some continuous function of $\beta$ (which you can explicitly write out if you want to), and thus so is each entry of $M'=BMB^t$.
We claim that the angle of rotation $\alpha'$ of $M'$ is also a continuous function of $\beta$. This is both somewhat obvious (since $M'$ has entries that vary continuously in $\beta$) and somewhat delicate -- essentially we can imagine $M'$ "moving around $SO_3$" (with respect to some standard topology), in which case the statement that the angle of rotation of $M'$ (at least away from the identity transformation) is continuous in $M'$. I'm sure it's also possible to write out a completely algebraic proof of this fact by explicitly finding the angle of rotation in terms of the entries of $M'$, but doing that doesn't seem particularly useful.
So, $\alpha'$ is a continuous function of $\beta$, but on the other hand we know that $\alpha'\in\{\alpha,-\alpha\}$. So, we can't have $\alpha'(\beta_1)=\alpha$ and $\alpha'(\beta_2)=-\alpha$ for some $(\beta_1,\beta_2)$, as otherwise $\alpha'$ would have to jump from $\alpha$ to $-\alpha$, which can't happen. So, if $\alpha'(\beta)=\alpha$ for some $\beta$, it is $\alpha$ for all $\beta$. It's not hard to see that $\alpha'(0)=\alpha$, which gives the desired conclusion.
Comment: Thank you for your answer. I forgot the details about my question and the background but it helped me a lot nevertheless. Maybe I will study your answer more in detail later and make a comment. That's why I have not accepted it yet but I will still give you the points


How to pass a variable to a new window (WindowGroup)?

Question: I'm trying to use the new WindowGroup to display a more complex view in a new window but somehow I can't figure out how to pass values into the view.
Until yet I was playing around with NSWindow but there I can't use the new toolbar with .toolbar{} and I'm somehow getting weird errors when using the latest swiftUI features.
In my old code I just could pass my values into the new view like usual:
.simultaneousGesture(TapGesture(count: 2).onEnded {

      var window: NSWindow!

      if nil == window {
           let serverView = serverView(content: content) // parse my struct content(name: "XServe-Test", configFile: "/FileUrl", permissions: .rootPermissions, cluster: cluster(x12, CPUMax: .cores(28), ramMax: .gb(1200)))
           window = NSWindow(
           contentRect: NSRect(x: 20, y: 20, width: 580, height: 400),
           styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered,
            defer: false)
            window.center()
            window.setFrameAutosaveName("ServerMainView")
            window.isReleasedWhenClosed = false
            window.title = content.name
            window.contentView = NSHostingView(rootView: serverView)
            window.toolbar = NSToolbar()
            window.toolbarStyle = .unifiedCompact
         }

      window.makeKeyAndOrderFront(nil)
 }

Now I'm using in the app file:
import SwiftUI

@main
struct myApp: App {

    var body: some Scene {

        WindowGroup {
            contentView()
        }.windowStyle(HiddenTitleBarWindowStyle())
        .commands {
            SidebarCommands()
            ToolbarCommands()
        }

        // the view that should be displayed in a new window
        WindowGroup("serverView") {
            let inputContent : content = content(name: "XServe-Test", configFile: "/FileUrl", permissions: .rootPermissions, cluster: cluster(x12, CPUMax: .cores(28), ramMax: .gb(1200)))
            serverView(content: inputContent) // this is static now :(
        }.handlesExternalEvents(matching: Set(arrayLiteral: "serverView"))
}

and the following code to open the view:
  .simultaneousGesture(TapGesture(count: 2).onEnded {

  guard let url = URL(string: "com-code-myApp://serverView") else { return }
        NSWorkspace.shared.open(url)
}

How do I pass the input from the tap gesture into the new view using the WindowGroup logic?
Comment: I'm looking for a similar solution. Did you find a way to do this?
Comment: @ZS check out my answer!
Answer: I found two ways to solve this problem. I'm using the first one, because my application is file based. The second solution is based on the great Pulse git repo.
In both cases you need to register a custom URL in the Xcode project settings under:
Tragets -> yourApp -> Info -> URL Types, otherwise it won't work.

first solution:
import SwiftUI

@main
struct myApp: App {

    var body: some Scene {
        // 'default' view
        WindowGroup { contentView() }

        // the view that should open if someone opens your file
        WindowGroup("fileView") { fileView() }
        .handlesExternalEvents(matching: ["file"]) // does the magic

    }
}

struct fileView: View {
    var body: some View {
        VStack{ /* your view content */}
        .onOpenURL(perform: { url in
            // get url and read e.g.: your info file
        })
    }
}

// you can open a file using:
Button("openMyFileinAnExtraWindow"){
   let fileUrl = URL(fileURLWithPath: "~/Documents/myFile.yourExtension")
   NSWorkspace.shared.open(fileUrl)
}

second solution:

Notice: I created this code snippet based on the great Pulse git repo.

import SwiftUI

@main
struct myApp: App {

    var body: some Scene {
        // 'default' view
        WindowGroup { contentView() }

        // the view that should open if someone opens your file
        WindowGroup { DetailsView() }
        .handlesExternalEvents(matching: Set(arrayLiteral: "newWindow")) // this url must be registerd

    }
}

struct DetailsView: View {
    var body: some View {
        ExternalEvents.open
    }
}

public struct ExternalEvents {
    /// - warning: Don't use it, it's used internally.
    public static var open: AnyView?
}

struct contentView: View {
    var body: some View {
        VStack {
            // create a button that opens a new window
            Button("open a new window") {
                ExternalEvents.open = AnyView(
                    newWindow(id: 0, WindowName: "I am a new window!" )
                )
                guard let url = URL(string: "your-url://newWindow") else { return }
                NSWorkspace.shared.open(url)
            }

        }
    }
}

struct newWindow: View {
    var id: Int
    var WindowName: String
    var body: some View{
        VStack{
            Text(WindowName + String(id))
        }
    }
}

I'm not sure if this is the best way to pass variables to a new window, but it does the job quite convincingly.
I'm happy about any solution approaches and ideas.
Comment: Thanks for the update. But in the first solution, I'm not clear how to pass in the filename that you want to open from the Tap Gesture recognizer to the new window you want to open. Do you still call `NSWorkspace.shared.open(url)`? And the `fileView` can handle it without needing to register as a URL type?
Comment: @ZS Yes you just open file via `NSWorkspace.shared.open(fileUrl)` or by double clicking it on the finder, I'm not sure if it is working with lets say a .txt file or only with custom files like .myFile etc.. Im using my own exported type identifier and it's working fine - even when opening the file with the terminal.
Comment: Thanks. I did get it to work now. I'm pretty sure that one would have to add the URL scheme even in the first example you showed. If you can add the details in your answer on how to invoke the URL (which you put in the question), I'll mark it as the correct answer.
Comment: @ZS I added the two details.
Answer: I found this example at Apple Developer
First, You need Codable & Hashable struct for your data. For example, If I would like to pass an url when opening a view:
struct File: Codable, Hashable {
    var id = UUID()
    let path: URL
}

Now we can pass this struct between windows.
@main
struct myApp: App {

    var body: some Scene {
        // Default View
        WindowGroup {
            ContentView()
        }

        // Open FileView() with given data.
        WindowGroup(id: "file.view", for: File.self) { $file in
            FileView(file: $file)
        } default: {  // fallback
            File(path: URL(string: ""))
        }
    }
}

FileView should look like below:
struct FileView: View {
    @Binding var file: File

    var body: some View{
        Text(file.path.absoluteString)
    }
}

You can open FileView() everywhere. This is an example to open FileView() with data in ContentView()
struct ContentView: View {
    @Environment(\.openWindow) private var openWindow
    @Environment(\.dismissWindow) private var dismissWindow

    var body: some View{
        Button("hit me") {
            openWindow(id: "file.view", value: File(path: URL(string: "file://")!)
        }
    }
}

Comment: Naming a property of type `URL` "path" is confusing. I'd stick with "url".


image is overflowing other div elements in css

Question: I am learning CSS basics and don't understand this. Why image is larger than div class where he is at. Div class has specified width and height, but anyway image is much larger.
Link to image example
The html code is like this

<a <%= link_to image_tag ('ecotechno_logo.png'), %>

CSS for logo
#logo{
display: block;
padding:15px 0 0 30px;
float:left;
width: 268px;
height: 96px;
clear:both;

I am quite new in this, so any help will be appreciated
:) Thanks
Comment: `` what does it render ?
Comment: is  overflow: hidden what you want or scaling the image?
Answer: You need to modify the html code

<%= link_to image_tag ('ecotechno_logo.png'), '#' %>

in css
#logo a img{
  width: 100%;
}

Answer: You need to set the width and height of the image as well.
something like:
#logo img { width:100px;height:100px; }

Feel free to change the '100px' to the size of the image that you want
Comment: Thanks, It worked, I will accept as answered after 8 minutes :)
Comment: But how can I assure right aspect ratio for image. because now it looks very creepy. It can be done using CSS or I have to create resized image and then just use .logo img {width:auto;height:auto;} ?
Comment: in regards to the div#logo size, you can set width:100%;height:100%; and just to be safe, you can also add display:block;
Answer: Add your image url to an img tag of format:

And you have to specify your width and height on the image not on the div. You can do this in css or on the element itself.
Answer: If you want the image to get truncated, use
overflow: hidden

in the parent container.
If otherwise you want the image to get scaled to the container width use
#logo {width: 268px;}
#logo img { width: 100%}

Answer: Use the Following code:
HTML

<a id="image" <%= link_to image_tag ('ecotechno_logo.png'), %>

CSS
#logo{
display: block;
float:left;
clear:both; }

#image{
margin:15px 0 0 30px;
width: 268px;
height: 96px; }

Answer: set for div, in css, overflow: hidden; and width and height for image, in css or in img tag.


How to pass multiple target_id/values field using entity reference prepopulate?

Question: I read the documentation and saw that this is possible: node/add/page?field_bar=1,2,3
But how do you code this? I wanted to pass multiple target id, not just one.
I tried this code but this only passes 1 value which is the first field value.
<?php
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$node->field_product_food['und'][0]['target_id'])  ));
echo $l;
?>

I also tried using an array loop like this:
<?php
$nids = array();
foreach ($node->field_product_food[$node->language] as $index => $item) {
$nids[] = $item['target_id'];
}
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$nids)  ));
echo $l;
?>

but the result is not like the example from the documentation.
Can somebody help me?
Thank you very much!
Answer: So if you want to create this link: node/add/page?field_bar=1,2,3
You need to put a comma between each nid, so implode() is what you want.
E.g.
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' => implode(',', $nids))  ));

Comment: OMG it worked! you're a life saver.. thank you my friend.. :D


$A\geq 0$ a.s., $E[A^a]<1,E[A^{a+d}]<\infty$. Show: $\exists e>0,g\in(0,1): \forall z\in [-e,e]:\mathbb{E}[(A/g)^{a+z}]<1$.

Question: Assume a random variable $A\geq 0$ a.s., $\exists \: \alpha,\delta>0: \mathbb{E}[A^\alpha]<1, \: \mathbb{E}[A^{\alpha+\delta}]<\infty$. Show: $\exists \: \epsilon>0: \: \exists \: \gamma\in(0,1): \: \forall z\in [-\epsilon,\epsilon]: \: \mathbb{E}[(A/ \gamma)^{\alpha+z}]<1$.
This problem is quite intuitive since $\alpha 's \text{ and } (\alpha+\delta) 's$ moment of $A$ and all the moments in between exist and also $\mathbb{E}[A^\alpha]$ is strictly less than 1, so there is still some gap before reaching 1, but how do I show it mathematically rigorous, analytically?
Thank you very much for your help!
Answer: I will assume that $a$ and $d$ are positive.
Hints:
Step 1: There exists $g \in (0,1)$ such that $E(\frac A g)^{a} <1$. [You have to to take $g$ close to $1$].
Step 2. $(\frac A g)^{a+t}\leq (\frac A g)^{a}+(\frac A g)^{a+d}$ if $|t| \leq d$. [Consider the cases $\frac A g \leq 1$ and $\frac A g > 1$ separately.
Step 3. $E(\frac A g)^{a+t} \to E(\frac A g)^{a}<1$ as $t \to 0$ by DCT.
Now you can finish the proof.
Comment: Great! Thank you!


How to increase size of FAB in flutter?

Question: How to increase size of FAB in flutter without size changing when route changes?
Following is the code for creating a custom FAB in flutter:
class FAB extends StatelessWidget {
  const FAB({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      width: 80,
      child: FittedBox(
        child: FloatingActionButton(
          backgroundColor: Colors.transparent,
          elevation: 0,
          child: Container(
            padding: EdgeInsets.all(12),
            height: 60,
            width: 60,
            child: SvgPicture.asset(
              logo,
              color: Color.blue,
            ),
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                    colors: [Colors.blue, Colors.red],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter),
                boxShadow: [
                  BoxShadow(
                    blurRadius: 16,
                    color: Colors.blue.withOpacity(0.64),
                    offset: Offset(0, 12),
                    spreadRadius: -6,
                  ),
                ]),
          ),
        ),
      ),
    );
  }
}

Here I'm resizing the FAB using a fitted box to a desired size.
But the issues is that whenever there is a route change the FAB appears small then becomes big (between route transitions). I think this is because I'm scaling the FAB to a desired size. I tried removing the fitted box and the container wrapping it. Then there is no issue.
Is there a way to scale the FAB without this issue?
This is the issue:
Comment: have you tried using an animated container so that you can control the behaviour?
Comment: Not sure of that!
Comment: You should try  https://pub.dev/packages/convex_bottom_bar
https://pub.dev/packages/ff_navigation_bar  packages
Comment: No. I don't want to use that. I have a custom layout. as you can see above.
Answer: Add height to your container and remove the FittedBox
Container(
  margin: EdgeInsets.only(top: 20),
  width: 80,
  height: 80,
  child: FloatingActionButton...

Comment: I tried that. then the size of the FAB won't increase!
Comment: Remember that I want to increase the size of FAB along with this!
Comment: I also tried transform.scale and a lot other tricks. I tried removing the FAB and added a custom button in place of FAB (within a stack). Then also there are other issues encountered like gesture not recognised beyond a size, etc... So this is the only way seems working for me. But the issue of changing size when routing changes need to be tackled.

How to increase size of FAB in flutter?


Preprocess function trying to alter title

Question: I have used this code in template.php.
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($node->title);
}

I was trying to alter the page title, and wanted to make a test before. When I use that code, the title disappears from the teaser. Do you know why?
Answer: template_preprocess_node() uses the following code.
  $variables['node'] = $variables['elements']['#node'];
  $node = $variables['node'];

  $variables['date'] = format_date($node->created);
  $variables['name'] = theme('username', array('account' => $node));

  $uri = entity_uri('node', $node);
  $variables['node_url'] = url($uri['path'], $uri['options']);
  $variables['title'] = check_plain($node->title);

It is perfectly fine, to set $variables['title'] in hook_preprocess_node() instead of calling drupal_set_title()/drupal_get_title(). The error in the code shown by the OP is not setting the local $node variable. The correct code is the following one.
// Drupal 7
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($variables['node']->title);
}

In Drupal 8, the equivalent for the code I wrote would be the following one.
// Drupal 8
function mytemplate_preprocess_node(&$variables) {
  $variables['label'] = "trial" . check_plain($variables['node']->label());
}

This would not change the title used for the <title> though. If you need to change that as well, you should use the following code.
// Drupal 7
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($variables['node']->title);
  drupal_set_title("trial" . check_plain($variables['node']->title), PASS_THROUGH);
}

Comment: I have added $node = $variables['node']; and it works perfectly. I wanted to alter the title because i have a classifieds site where people tend to insert URLs in titles so to prevent this i wanted to test a function, for removing automatically URLS from it. So in that case i cannot use drupal_set_title() i think
Comment: You could use `drupal_set_title()`, and that would change the title used for the `` tag; if you don't need to change that, then you don't need to use `drupal_set_title()`.
Answer: You shouldn't be using that to alter the page title, you can just use drupal_set_title();
Answer: Also inducing title to the $variables array will not change the page title in the browser tab. So as already suggested page title can be set conditionally as below.
function mytheme_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your_content_type") {
    drupal_set_title("my_title");
  }
}

Comment: Just a question, My title alteration works on teaser view only, how to make it work on full view also ?
Answer: The title 'disappears' because you are assigning and undefined value to it. You're using $node, but that variable isn't in scope/defined.
Use:
$node = $variables['node'];
$variables['title'] = "trial" . check_plain($node->title);

Also, as Steven has already said, you should (ideally) use drupal_set_title() to set the page title. However, depending on when (in the page execution) you call this function, it may or may not affect the output of what you're seeing - it can be a bit tricky. It appears you're changing the title on the theme layer, at which point I'd say your approach is generally fine, but it may be nicer to do the change in something like template_preprocess_page(), instead.
Comment: Why my changes appear on teasers only and not on the titles of full nodes ?


Installing React in Meteor: Atmosphere or NPM

Question: I have been installing React into Meteor projects using
npm install --save react react-dom

What is the difference between doing that and using a package from Atmosphere:
meteor add reactjs:react

Answer: It's more like a consistency assumption rather a real deal.
You may install react via bower , NPM , Atmosphere or even by cloning the repository.
In my projects, I had clarified dependency management as:

Use NPM for backend dependencies ( using Node.js ) or frontend dependencies that require a building / piping / bundling system like Babel, Webpack or Gulp.
Use Bower for "presentation" dependencies like Bootstrap, jQuery or prebuilt modules used as is.
Use any additional package management tool for any further dependency injection.

TL;DR
There are no differences between the two approaches ( although Atmosphere is not mentioned as a proper way to install / build React into the official docs)
If you prefer to keep React rendered in the browser use NPM or Bower. If you need to use React mapped into Meteor backend's code as an isomorphic app you may use Atmosphere as it is semantically used as a dependency.


Get all points in an ellipse knowing the center, one point, the vertical axis and the horizontal axis

Question: How to get all the points in an ellipse when I know a point of it and it's center?
I have the following situation:

I know the position of the red dot relative to the center, I have the vertical distance and the horizontal distance values. What I need is to calculate all the other possible points in the ellipse, as to know what other points the dot can be if it orbits the ellipse.
I have a coordinate system to make that
How is it possible to be done?
@EDIT
I'm also able to know the major axis and the minor axis
Comment: You can't. You can draw an infinite number of ellipses with the same centre that pass through a given point.
Comment: What do you need it for? Maybe you have some additional information you did not consider?
Comment: Generally an ellipse can be defined by two foci and a point lying on it, two foci and the sum of the distances from the foci for a point on the boundary, or by the center and its major and minor radii (and the direction of one of the radii).
Comment: I'm able to know the horizontal radii and the vertical radii
Comment: @YuriyS title edited. I do have a coordinate system, but I don't know the equation x=
Comment: The answer is still not unique, since you can reflect the ellipse across the line between the center and your point.  But there should be only two possibilities.
Comment: @Eric I'm able to test the possibilities, to see what's the one I want, but I don't know how to develop the equation
Answer: Let $a,b$ be the major and minor axes of the ellipse.
Let $x_0,y_0$ be the coordinates of the center on the ellipse.
Let $x_1,y_1$ be the coordinates of the one point on the ellipse.
First, we write the equation of the ellipse, those major axis is parallel to the $x$ axis of the coordinate system (which is at this point completely arbitrary).
$$\frac{(x-x_0)^2}{a^2}+\frac{(y-y_0)^2}{b^2}=1$$
Now we need the ellipse to go through the point $x_1,y_1$. This requires first that the distance between this point and the center is somewhere between $a$ and $b$:
$$b \leq \sqrt{(x_1-x_0)^2+(y_1-y_0)^2} \leq a$$
If it's indeed true, we need to find the four corresponding points on the ellipse on the same distance from the center.
$$d=\sqrt{(x_1-x_0)^2+(y_1-y_0)^2}$$
One of them is a green point on the picture below:

We need to find the green point. Let's call it $x_2,y_2$. Then we have two equations in two variables:

$$\frac{(x_2-x_0)^2}{a^2}+\frac{(y_2-y_0)^2}{b^2}=1$$
$$(x_2-x_0)^2+(y_2-y_0)^2=(x_1-x_0)^2+(y_1-y_0)^2$$

After you solve this simple system of equations and find $x_2,y_2$, there is one last step left: you need to rotate your ellipse.
First, find the angle between lines going from the center of the ellipse to $x_1,y_1$ and to $x_2,y_2$. You can do it by using vector dot product:

$$\cos \theta=\frac{(x_1-x_0)(x_2-x_0)+(y_1-y_0)(y_2-y_0)}{\sqrt{(x_1-x_0)^2+(y_1-y_0)^2}\sqrt{(x_2-x_0)^2+(y_2-y_0)^2}}$$

The rotated coordinates can be then found from the following system of equations:
$$x=X \cos \theta-Y \sin \theta \\ y=X \sin \theta+ Y \cos \theta$$
Note, that I inverted the problem - as if the ellipse is already rotated counter-clockwise, and we want to rotate it back. Meaning, we just substitute these formulas in the original equation:

$$\frac{(X \cos \theta-Y \sin \theta-x_0)^2}{a^2}+\frac{(X \sin \theta+ Y \cos \theta-y_0)^2}{b^2}=1$$

And here is the equation for your ellipse. You still need to find $x_2,y_2$ and $\cos \theta$ - I leave it to you.
See http://en.wikipedia.org/wiki/Rotation_matrix for more about rotation.
Note, that there is four possible green points you can choose, so there is four different equations you might need to check, not two.


Identifying rings of bounded functions

Question: Let $S$ be the subset of $\mathbb{R}^2$ defined by the inequalities
$$0\le\sqrt{2}x-y<1.$$
The set of polynomials in the ring $\mathbb{R}[x,y]$ that are bounded on $S$ obviously forms a subring $B$. I suspect that $B=\mathbb{R}[\sqrt{2}x-y]$.  Can anyone suggest a proof or a counterexample?
Answer: $X \mapsto \sqrt{2}x - y$ and $Y \mapsto y$ defines an isomorphism from $\mathbb{R}[X, Y]$ to $\mathbb{R}[x, y]$. In  $\mathbb{R}[X, Y]$ you are asking which polynomials are bounded in the strip $0 \le X < 1$. But if $f = f(X, Y)$ is bounded for $X = 1/2$ say, all the coefficients of $Y$ must vanish,  hence $f \in \mathbb{R}[X]$. Your claim now follows by pulling this back into $\mathbb{R}[x, y]$.
Comment: Yes, thank you. This is what I was looking for.
Answer: The inclusion $\mathbb R[\sqrt 2 x-y]\subseteq B$ is clear.
Consider the algebra homomorphism $\phi\colon \mathbb R[x,y]\to\mathbb R[t]$ given by $x\mapsto t$, $y\mapsto \sqrt 2 t$.
The kernel of $\phi$ is precisely $\mathbb R[\sqrt 2 x-y]$.
Let $f\in B$. We want to show $\phi(f)=0$.
Assume $\phi(f)\ne 0$.
Then $\phi(f)$ is not bounded and for each $M$ we can pick $\tau_M\in\mathbb R$ with $|\phi(f)(\tau_M)|>M$.
But then also
$|f(\sqrt 2\tau_M,\tau_M)|=|\phi(f)(\tau_M)|>M$ with $(\sqrt 2\tau_M,\tau_M)\in S$, i.e. $f$ is not bounded on $S$.
Comment: The kernel of $\phi$ cannot be a subring: For example, clearly $1\in B$, but $\phi(1)\ne 0$.

Identifying rings of bounded functions


What is the minimum time needed for Shubrata and Amlan to eat 252 jackfruits?

Question:
Once Shubrata and Amlan ate 50 jackfruits in total for 3
  hours and 5 hours respectively. Another time they ate 200
  jackfruits for 26 hrs and 10 hrs respectively. Now what is the
  minimum time needed for them to eat 252 jackfruits?

Source: Bangladesh Math Olympiad 2016 Junior Catagory
I can not understand the ratio of the time in this question. The second statement makes me more confused.
Comment: I'm not sure that I understand the question. What does "respectively" mean, precisely, in this case? Does the first one mean that Shubrata ate 50 of them in 3 hours? And there was another set of 50, that Amlan ate? Or did they share them and Shubrata gave up for some reason, two hours before Amlan?
Comment: Maybe you have to approach this by considering a "jackfruit eating capacity" that each of them have, and it's a constant value for a person.
Answer: Let $x,y$ denote the number of jackfruits Shubrata and Amlan have eaten per hour. Then $3x+5y=50$
We also know that $26x+10y=200 \implies 13x+5y=100$.
Hence, $100-13x = 50-3x \implies 10x = 50 \implies x=5$ and $5y=50-15=35 \implies y=7$
Now, we're looking for the minimum amount of time it takes these two people to eat $252$ jackfruits. We're looking for time $t$ such that $5t+7t=252$. Hence, $12t=252$ and $t=21$ hours.
Answer: I would interpret the wording of such a question this way:
On the first occasion, Shubrata spent $3$ hours eating jackfruits and Amlan spent $5$ hours eating jackfruits. Together they ate $50$ jackfruits on this occasion,
that is, if Shubrata ate $S$ jackfruits and Amlan ate $A$ then $S + A = 50.$
On the second occasion,  Shubrata spent $26$ hours eating jackfruits and Amlan spent $10$ hours eating jackfruits. Together they ate $200$ jackfruits on that occasion.
I think we're meant to assume that each person has the ability to eat some number of jackfruits per hour,
and the same person can go on hour after hour eating the same number of jackfruits,
although a different person might be able to eat a different number of jackfruits each hour.
Then from the two given occasions we can figure out how many jackfruits Shubrata eats each hour and how many Amran eats each hour.
Finally, I suppose that "minimum time" means that at some instant we supply the $252$ jackfruits, so that Shubrata and Amlan can eat them, after $T$ hours we observe that all the jackfruits have been eaten, and we want this to be done in such a way that $T$ is as small as possible.
This is done when both Shubrata and Amlan spend the entire $T$ hours eating jackfruit so that no time is wasted.
Mind you, jackfruit is tasty, but I do not think anyone can eat so many jackfruit as either of these two, hour after hour, and not burst.
Comment: +1 for jackfruit comment. I dislike problems from the "real world" that are completely unrealistic.
Answer: Say that Shubrata can eat $x$ jackfruits per hour and Amlan can eat $y$ jackfruits per hour. So you have:
$$3x+5y=50$$
$$26x+10y=200$$
Can you proceed from here? The answer is 21 hours.
For those curious, here is how jackfruit looks like :)


Who are the "Olympic Athletes from Russia"?

Question: Who are the "Olympic Athletes from Russia"?
I was watching the 2018 Winter Olympics and saw "Olympic Athletes from Russia." Why isn't this done for other countries such as "Olympic Athletes from the United States" or "Olympic Athletes from Italy"?
Comment: Relevant Wikipedia articles: [Olympic Athletes from Russia at the 2018 Winter Olympics](https://en.wikipedia.org/wiki/Olympic_Athletes_from_Russia_at_the_2018_Winter_Olympics) and [Independent Olympians at the Olympic Games](https://en.wikipedia.org/wiki/Independent_Olympians_at_the_Olympic_Games)
Answer: The Russian Olympic Committee was suspended from the 2018 Pyeongchang Winter Olympic Games as a result of state-sponsored doping and testing fraud in the 2014 Sochi Winter Olympic Games. They are disallowed from any national presence at the Games. 42 Russian athletes were banned and had medals stripped as a result.
Athletes from Russia were permitted to apply and compete individually (respectively, as individual teams in sports such as curling or bobsled) apart from

28 whose bans were overturned but remain uninvited
11 whose appeals against bans were denied
3 whose appeals will not be completed until after the Games end

along with those who did not otherwise qualify or meet the conditions required.
After passing all tests and meeting conditions, 169 athletes were permitted to compete as Olympic Athletes from Russia (OAR). As with previous cases, they compete as independent athletes wearing a neutral uniform under the Olympic flag with the Olympic anthem.
Answer: @Nij's answer explains the background for why and how this happened, but I just want to give a very simple explanation for the immediate question:

Who are the "Olympic Athletes from Russia"?

They are "Olympic Athletes" who are "from Russia", but not part of the Russian team. (Because there is no Russian team, as explained in @Nij's answer.)

I was watching the 2018 Winter Olympics and saw "Olympic Athletes from Russia." Why isn't this done for other countries such as "Olympic Athletes from the United States" or "Olympic Athletes from Italy"?

Because they are part of the US and Italian teams, not just Olympic Athletes who happen to be from the US and Italy.


The entityManager.remove(class) is not working

Question: I got this method under a public class named Utilidades:
  public void delete(TipoUsuario tipoUsuario) throws Exception {
        if (em != null && tipoUsuario != null) {
            try {
                System.out.println("NO SON NULOS");
                // TipoUsuario p = em.find(TipoUsuario.class, tipoUsuario);
              em.getTransaction().begin();
//                Query query = em.createQuery("DELETE FROM TipoUsuario t WHERE t.idTipoUsuario = :idTipoUsuario");
//                query.setParameter("idTipoUsuario", tipoUsuario.getIdTipoUsuario());
//                int rows = query.executeUpdate();

               // if (em.contains(tipoUsuario)) {
                  //  em.remove(tipoUsuario);
               // } else {
                    em.remove(em.merge(tipoUsuario));
               em.getTransaction().commit();
             //   }

            } catch (EntityNotFoundException enfe) {
                Logger.getLogger(Utilidades.class.getName()).log(Level.SEVERE, enfe.getMessage(), enfe);
                em.getTransaction().rollback();
            }
        } else {
              System.out.println("NULOS");
        }
    }

I am injecting this class in a servlet and using this delete method but is not deleting the row
 String st = request.getParameter("txtIdUsuario").trim();
if (!(st == null || "".equals(st))) {
                    idUsuario = Integer.parseInt(st);
                }
                tipoUsuario.setIdTipoUsuario(idUsuario);
out.println("
Se selecionó botón " + idUsuario + " eliminar
 ");
                        utilidades.delete(tipoUsuario);
                        out.println("
Se selecionó botón eliminar
 ");

Do you guys have an idea of how can i do in order to delete a row?
Comment: why `em.merge` ?
Comment: So you are sure the method is being called and there is no exception?
Comment: You merge some changes in and then (want to) delete them?! Makes no sense. What does your debugging tell you? like looking at the LOG of the JPA provider? SQL invoked ?
Answer:
Usually, we fetch from db to make sure the entity exists. Like
FROM TipoUsuario WHERE NAME = :name;
Query query = em.createNativeQuery("FROM TipoUsuario WHERE NAME = :name;", TipoUsuario.class)
        .setParameter("name", name);

TipoUsuario tipoUsuario = null;

try
{
    tipoUsuario = (TipoUsuario) query.getSingleResult();
}
catch ( Exception e )
{
    return null;
}

Make sure NAME is the primary key of table TipoUsuario.
If you have the id of TipoUsuario, you can fetch the entity by
em.find(TipoUsuario.class, id);

Anyway, you get the result you want. Then you do

em.remote(tipoUsuario);
to remote it. That's it.
Your issue exists that you just set one value of an object of TipoUsuario, but it is not the same result in table.
So em.merge(obj) just inserts a new row in table. Then you remove the new row. So the old row still exists in table.
Comment: Thanks, you gave me a good idea. This is what i did and it worked:

                em.getTransaction().begin();
                TipoUsuario user = em.find(TipoUsuario.class, tipoUsuario.getIdTipoUsuario());
                em.remove(user);
                em.getTransaction().commit();


Acessar um textField que está dentro de um gridPane em javafx

Question: Tenho estado a desenvolver um trabalho de mestrado em javafx: algo que recebe uma imagem, coloca uma grelha com textFields em todas as células por cima da imagem.
O utilizador depois pode colocar valores nos textFields. A grelha é criada automaticamente, dependendo do número de linhas e colunas que o utilizador pretender.
Esta é a minha class controller da view:
package vistas;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ResourceBundle;

import javax.print.DocFlavor.URL;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.stage.FileChooser;

import principal.main;

public class AreaProjectoController {

    @FXML
    private Button meuBotaoImagem, meuBotaoGrelha, btnLimpaGrelha, btnArea;

    @FXML
    private ImageView minhaImagem;

    @FXML
    private TextField txtGrelhaLeft, txtGrelhaRight;

    @FXML
    private AnchorPane painelGrelha, painelArea;

    @FXML
    private GridPane painelCriaGrelha;

    public void initialize(URL location, ResourceBundle resources) {
    }

    public void mostraImagem(ActionEvent evento) throws FileNotFoundException {

        FileChooser imagemEscolhida = new FileChooser();

        // Define a extensão do ficheiro
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG/PNG", "*.jpeg", "*.png");
        imagemEscolhida.getExtensionFilters().add(extFilter);

        // abre a janela para procurar uma imagem
        File ficheiro = imagemEscolhida.showOpenDialog(main.getPrimaryStage());

        // O if trata quando se cancela o carregamento de uma imagem
        if(ficheiro != null) {
            Image imagem = new Image(new FileInputStream(ficheiro));
            minhaImagem.setImage(imagem);
            painelGrelha.setVisible(true);
            txtGrelhaLeft.setText("0");
            txtGrelhaRight.setText("0");
        }

    }

    public void criaGrelha(ActionEvent evento) throws FileNotFoundException, IOException {

        int txtLeft = 0, txtRight = 0, i = 1, ii = 1, l = 0, j = 0;

        ColumnConstraints colunas = null;
        RowConstraints linhas = null;

        txtLeft = Integer.parseInt(txtGrelhaLeft.getText());
        txtRight = Integer.parseInt(txtGrelhaRight.getText());

        //Este for cria a grelha após receber os valores
        for(i = 1; i <= txtLeft; i++) {
            colunas = new ColumnConstraints();
            colunas.setPercentWidth(25);
            painelCriaGrelha.getColumnConstraints().add(colunas);
        }

        for(ii = 1; ii <= txtRight; ii++) {
            linhas = new RowConstraints();
            linhas.setPercentHeight(25);
            painelCriaGrelha.getRowConstraints().add(linhas);
        }

        //Label fillLabel[][] = new Label[txtLeft][txtRight];
        TextField fillLabel[][] = new TextField[txtLeft][txtRight];

        for (l = 0; l < txtLeft; l++) {
            for (j = 0; j < txtRight; j++) {
                fillLabel[l][j] = new TextField();
                //fillLabel[l][j] = new Label();
                fillLabel[l][j].setText(String.valueOf(0));
                fillLabel[l][j].setBackground(null);
                painelCriaGrelha.add(fillLabel[l][j], l, j);

            }
        }

        /*for (l = 0; l < fillLabel.length; l++) {
            for (j = 0; j < fillLabel.length; j++) {
                System.out.println(fillLabel[l][j].getText());
            }
            System.out.println(" ");
        }*/

        painelCriaGrelha.setGridLinesVisible(true); //isto faz aparecer as linhas da grelha a preto
        painelArea.setVisible(true);

        //for(l = 1; l <= fillLabel.length; l++) {

        //System.out.println(l);
    //  }

        //Func.salvaInfoGrelha(listaElementosArea);

    }

    public void limpaGrelha(ActionEvent evento) {

        painelCriaGrelha.getColumnConstraints().clear();
        painelCriaGrelha.getRowConstraints().clear();
        txtGrelhaLeft.setText("0");
        txtGrelhaRight.setText("0");

    }

    public void defineArea(ActionEvent evento) {

        int txtLeft = 0, txtRight = 0;
        int l = 0, j = 0;

        txtLeft = Integer.parseInt(txtGrelhaLeft.getText());
        txtRight = Integer.parseInt(txtGrelhaRight.getText());

        TextField fillLabel[][] = new TextField[txtLeft][txtRight];// = new S[txtLeft][txtRight];
    //GridPane painel = new GridPane();

    System.out.println(txtLeft);
    System.out.println(txtRight);

    //TextField texto = fillLabel[1][1];

    painelCriaGrelha.getChildren().get(fillLabel[1][1].getText());
    System.out.println(painelCriaGrelha.getChildren().get(fillLabel[1][1]).getText());

        /*for (l = 0; l < txtLeft; l++) {
            for (j = 0; j < txtRight; j++) {
                System.out.println(painelCriaGrelha.getChildren().get(fillLabel[1][1]));
            }
        }*/

        //System.out.println(texto);

    }

}

A minha dúvida está na última função.
No fim do utilizador preencher as células e clicar no botão "defineArea" era suposto conseguir guardar os valores da grelha numa Array.
Tentei converter para Int, mas também não consegui.
Não consigo acessar o conteúdo dos textField da gridPane, talvez não estou construindo a minha função corretamente, mas acho que estou a pensar bem, quando tenho acessar com a linha:
painelCriaGrelha.getChildren().get(fillLabel[1][1]);

Answer: o método getChildren() retorna um objeto tipo Node, vc deve perguntar se o node é de tipo TextField. Pode perguntar:
  if(node instanceof TextField)

e depois fazer o seguinte;
 ((TextField)painelCriaGrelha.getChildren().get(fillLabel[1][1])).getText();


LilyPond piano score: switching between alternating and simultaneous chords

Question: I have piece of piano music that has two parts. In one part, chords are alternating between hands but I don't want to express staves precisely to leave it for a player. In the second part, the hands are playing together. I have problem regarding how to switch between \autochange and explicitly staving. Please look at the piece below:
\score{
    \new PianoStaff \chordmode {
        \new Staff = "up" {
            \autochange {
                \repeat unfold 4 { c,,8 c' }
            }
            {
                \repeat unfold 4 { c'' d'':m }
            }
            \new Staff = "down" {
                \clef bass
                \repeat unfold 4 { c,,8 d,,:m }
            }
        }
    }
}

The first bar is okay - there are no rests. But the second two bars should be combined together.
Answer: The problem is that \autochange is doing too many things automagically, and doing them in the wrong place. Specifically, it is creating two staves called "up" and "down", but the "down" staff is nested inside the first block of your score, and you are then creating another staff called "down".
One solution is to set up the staff structure of the PianoStaff explicitly, and put the \autochange inside that structure.
In the version below, the "down" staff starts from the beginning of the score, so you need the s1 to skip past the first bar.
Note, \context is similar to \new, except that all \contexts with the same name refer to the same object. In effect, that means you can refer to the "up" and "down" staves before \autochange has actually created them.
\score {
    \new PianoStaff <<
        \context Staff = "up" {
            \autochange {
                \chordmode {
                    \repeat unfold 4 { c,,8 c' }
                    \repeat unfold 4 { c'' d'':m }
        } } }
        \context Staff = "down" {
            \chordmode {
                s1
                \repeat unfold 4 { c,,8 d,,:m }
        } }
    >>
}

Actually, the way the above solution is structured is a bit convoluted. This is might be easier to understand and extend. The autochange creates the "up" and "down" staves, and the contexts then add more music to them. Then you must remember to define rhythm values for both staves.
\score {
    \new PianoStaff <<
        \autochange {
            \chordmode {
                \repeat unfold 4 { c,,8 c' }
        } }
        \context Staff = "up" {
            s1
            \chordmode {
                \repeat unfold 4 { c''8 d'':m }
        } }
        \context Staff = "down" {
            s1
            \chordmode {
                \repeat unfold 4 { c,,8 d,,:m }
        } }
    >>
}


How to call a base class __init__ as self?

Question: How do I re-initialize the base class using self.__init__?
In the following example my goal is to inherit eComm which is a socket derived driver. This handles connect/disconnect. If it disconnects we need to reinitialize it using __init__, however it appears to refer to the comDriver when self.__init__ is called.
How do I properly initialize the superclass to allow for this?
(else: self.__init__ in connect() is referring to comDriver, not eComm like it should)
The following is a simple case to reproduce the error in Python 3.x
class eComm():

    def __init__(self):
        self.s = "example object"
        self.initialized = True
        self.connected = False

    def connect(self, IP_ADDRESS, PORT):
        if self.initialized:
            print(IP_ADDRESS, PORT)
        else:
            print("REINITIALIZING")
            self.__init__()
        self.connected = True

        return(True)

class comDriver(eComm):

    def __init__(self, IP_ADDRESS, PORT):
        self.IP = IP_ADDRESS
        self.PORT = PORT
        super().__init__()
        pass

    def getTemp(self):
        print("EXAMPLE FUNCTION")
        return(1)

x = comDriver("192", 7)

x.connect("161", 6)
x.initialized = False
x.connect("111", 5)

Comment: That's probably a bad use of Python's special method `__init__`. You may want to create a separate "initializer" method, and call it from `__init__`.
Comment: "If it disconnects we need to reinitialize it using `__init__`" - that's a bad idea. `__init__` really should only be used to set up new instances. While it's technically possible to call it on already-initialized instances, doing so leads to all kinds of headaches.
Answer: IMO you're using the special method __init__ wrongly. It's meant to initialize a Python object, not anything outside that scope.
With your intention, I recommend that you create a separate initializer function, and call it from __init__. Here's an example:
class eComm():
    def __init__(self):
        self.initialize_eComm()

    def initialize_eComm(self):
        self.s = "example object"
        self.initialized = True
        self.connected = False

And then you can replace self.__init__() with self.initialize_eComm() to avoid name conflict in subclasses.
Answer:
self.__init__ in connect() is referring to comDriver, not eComm like it should

This doesn't quite hold -- self refers to the calling object, which is comDriver. If you want to call to the __init__ method on eComm regardless of what classes extend it, you will have to reference in explicitly.
eComm.__init__(self)

But, the other answers and comments are right that this is not a good use of __init__.


The best laptop for a sysadmin

Question: For those of you who still not tired of "XYZ for sysadmin" questions: This subject is bothering me for a long time.
I had number of problems selecting notebook for job. For example:

Notebook vs Netbook is the real problem
too. First has more comfortable
keyboard and bigger screen and almost
always faster. Second is smaller and
easier to carry, but don't have
CD/DVD-RW;
14"/15"/17" screen. Don't see winner
here. 2-3 more xterms/windows on one
screen at cost of 1-2 more kg;
Number of extension ports is essential
I think. New Mac Air is good, but c'mon:
no LAN and two USB ports vs LAN and one USB.
Also, as sysadmin I really need COM port to
setup network equipment,
but where can you find notebook with
COM port in 2012? Problem was solved
by buying USB-COM cable, but still
have problems with drivers in some
OSes;

So here goes my questions:

What you think is good notebook
for sysadmin? May be you can list
specific models;
What hardware extensions(i.e. USB devices) you think should be added to "sysadmin must-have"
list;
Comment: Is a USB to Serial adapter acceptable?
Comment: Perhaps you could explain the requirement for more than one NIC?
Comment: @sparks, Yes USB-to-Serial is acceptable, but they have their issues, so built-in is better.

@Dan, From time to time I need to sniff traffic in bridge mode to see whats going on on network or sometimes when gateway dies, I can in couple of minutes setup my FreeBSD on notebook to pass traffic between networks while we figuring out what happened with GW. pjz suggested to use USB network card as second one.
Comment: Two NICs- monitor mirrored Gigabit port on one, surf ServerFault for answers on the other.
Comment: I had an experiences when there is no additional ports on hardware (i.e. PC router or Cisco 3620) or when there is need of changing header/content of packet on the fly. Otherwise you right - port mirror is good hack to do sniffing.
Comment: Not going to go into a long explanation of why, but I love my Lenovo T410 as a Linux Systems Admin.
Answer: I've gone pretty much 'USB everything' so all the extras stay in the bag until needed.  USB serial port, USB ethernet adapter ( I hear you about sometimes needing two NICs! ), USB CD/DVD-RW.  The weight still adds up on the shoulder, but the base machine then requires nothing more than a USB port (or two or three unless you also add a USB hub to the mix).  Also handy: USB card reader, USB headphones/mic, and USB->miniUSB cable (for cellphone charging), oh, and USB->IDE/SATA adapter for quick access to random drives from dead machines. Another advantage to USB is that you still have all the extras if/when you upgrade your notebook to another model!
Screensize is up to personal choice - I've gotten fast with my virtual desktop switcher and lived for a long time on an 800x600 13" screen, so my current 15" 1680x1050 seems absolutely luxurious.  Of course, more is always better, right? :)
Whatever you do, max out the RAM in your laptop to whatever your OS can use - you won't regret it when you're trying to read docs in firefox on one desktop and run wireshark in another and have a half dozen screen terms open...
Comment: Great writeup. Personally I don't think the screen size matters at all, as long as you are able to 'get things working' with it. I just went from 15" to 13" to 10" because simply I prefer having my laptop portable and a separate workstation for the heavy hits. USB has completely replaced the need for specific on board hardware imho.
Answer: For me, the perfect SA notebook is something that you can carry everywhere and always be to hand. That means light and small. Notebooks are too big and seem often designed for people to use on tables. Netbooks are just too small. Subnote 12" is perfect.
I have an HP 2510p presently, which they have just since released a new 2530p model of.

Weighs less than 1.5kg.
The screen is a WXGA, so capable of fitting enough information on and still readable.
Built-in DVD+/-RW, for burning new ISOs on the run.
Bluetooth, for tethering to a mobile.
Built-in UMTS/HSDPA, if you wish.
A good Synaptics trackpad, instead of just a nipple.
Different battery sizes available. I easily get 5hrs out of a medium pack.
Keyboard is perfectly good and not re-orientated like some.
Build quality is good.

IBM also make some nice subnotes. But the trackpad is a real clincher for me.
I think that now the only solution to serial is USB. If you can find a really small dongle based on a reliable chipset then the hassle is greatly reduced. I've had good experience with Prolific 2303 chipsets. Drivers are in the Linux kernel tree and easily available for Windows. They list some manufacturers on this page and this dongle is also meant to be perfectly good.
Answer: 15" Macbook Pro. Reasons:

I don't have to mess with the OS to make hardware function. As a sysadmin, I spend enough time doing that on servers.
OS X is a certified Unix, which speaks to my geekiness.
It has a full complement of shell tools pre-installed, with thousands more a 'port install' away.
The touchpad is the only one I've ever used (out of IBM, Dell, HP and Sony laptops) that doesn't make me want to scream, or at least use an external mouse.
It's far easier to get VPN software that "just works", whereas several VPN tools don't even run on Linux (or at least, didn't the last time I used it as a workstation).
The 1440x900 display means I can run heaps of terminals side-by-side and stacked on each other.
Expose and Spaces have become essential productivity enhancements, as I can separate out projects easier.

As someone who works from home and doesn't have to physically connect to systems in data centers, I don't need things like COM ports. Besides, hosting centers have people for that :-).
Answer: I do a fair bit of network engineering in the industrial/engineering sector and needed a laptop with a COM port for both switches and PLCs. The only real options that we found were old Dell Latitude D820s (as of about a year ago you could still purchase these if you told dell you needed the com port) and the Panasonic business rugged Toughbooks.
The toughbooks are great, a little pricey, but great. I've had better experiances with them than with the Dell's, which we found had some memory and CPU problems (bad_pool_caller bluescreens, extreemly slow startup occasionaly (4min+) with CPU going at 100% for no reason). Then again we bought a lot of the Dells and only demoed the toughbooks (the cheaper option won), so samplesize.
Edit: we were looking at these after about three USB to COM adapters and having no luck with Rockwell PLCs. I hear some manufacturers are now building PLCs with USB diagnostic ports, so maybe this won't be such a problem in 5-10 years.
Comment: It's still only anecdotal, but we had problems with every D820 we bought, too.

I used to do PLC programming (but Modicon), I'd certainly try one of the PCMCIA serial port cards from these guys:

http://startech.com/category/parts/io-cards-adapters/notebook-io-cards/list.aspx
Comment: Thanks, I've bookmarked that for when we next look at purchases.
Comment: If you are willing to get the panasonic tough books check out Itronix as well.  They have 9 pin serial on them.  http://www.gd-itronix.com
Comment: The panasonic "business rugged" toughbooks aren't really a rugged laptop, certainly not compared to their field rugged models. As such they're also a much lower cost than the field rugged toughbooks.
Comment: Most Dell Latitude notebooks have built-in 9-pin serial ports. Good for talking to those Rockwell PLCs you refer to.
Answer: We've been buying HPs for a few years now and so that's what I have.  Current model is a Compaq 6910p.  It's not the smallest or lightest, but it's not too big or too heavy.  I tried a first generation HP 2133 mini-note, but the screen size was too small on those (the first ones had speakers on either side of the screen, limiting the size).  For most of my work, the newer ones would be fine, but my 6910 is still going fine.
Feature I need in a "sysadmin" notebook:

I find the DVD drive to be critical, for burning disks, looking at installation disks.
As many USB ports as possible, I find I'm always using the 3 on my current laptop.  I carry a couple of small USB hubs, one powered, one not.
I usually don't carry a mouse, I'm fine with the touchpad and just leave a mouse on my desk for when I'm using it there.
A serial port would be nice, but there just aren't many laptops that come with them any more.  I do have a serial-usb converter, but I don't carry it around.  We have a bunch of older laptops and we leave one in each of the service corridors with the switches.
For my own backups, I've got an eSATA PCMCIA card that I use, but that's a "nice to have," not a requirement.
Answer: I use an old HP/Compaq nc4010.  It comes with two USB, a VGA port, a PCMCIA port, and a PS/2 port.  It has wifi and bluetooth as well as Ethernet and a telephone modem.
It is remarkably lightweight and quite compatible with Linux and OpenSolaris and FreeBSD.  I use the docking station (a/k/a HP Port Replicator) to get access to DVDs and CDROMs.  The machine is very light and portable, and the screen is clear and crisp.
For the serial port, I use a Keyspan USB-serial port: these are well supported by Linux and UNIX.
As for the mouse, the notebook has a trackpad and a "finger pointer" - take your pick.  The notebook is very easy to maintain and to replace parts; travel batteries (secondary batteries) are available.
Because of the age, you'll probably find great deals on the system, on parts, on the port replicator, and on the batteries on Ebay.
Comment: Having had an nc4010 in the past - try an 25x0p. They're an order of magnitude better!
Answer: My employer has standardized on IBM/Lenovo and i use a X200.
Capable CPU (2,5ghx dualcore)
Fast HDD (320GB 7200rpm)
Lot's of memory for using VM's on the fly (4GB)
3G for internet access anywhere
USB DVD-RW, if i rarely need it. Most stuff is done over LAN, including installs.
USB-COM, if i need it.
Plenty of battery (up to 6hrs offline with flush 6cell battery).
Light (about 1,5kg)
3 USB's for practically anything (IDE, SATA, Eth, phone etc)
Dock (can't live without it on my desk)
Dualboot Vista Enterprise and W2k8 Standard (for local Hyper-V).
Answer: Most Dell Latitude notebooks still have a built-in 9-pin serial port. We use them to communicate with some older PLC's whose software is so old that it can't seem to work properly with the USB->Serial Adapters.
Answer: i use a latitude d630.  since i'm outsourced it to multiple companies and on the road frequently, the verizon wan card gets used frequently.  a healthy battery is essential as well.  the only hardware i've had to purchase to supplement what it has was a usb floppy drive for 1 client.  all other work i handle through what is included hardware wise and software.

The best laptop for a sysadmin


Having trouble understanding this proposition from my textbook.

Question: I'm seeing this perplexing proposition in my optimization textbook:
Suppose an LP
$$\max\{z(x)=\vec{c}^{T}x+\bar{z}:A\vec{x}=\vec{b},\vec{x}\geq\vec{0}\}$$
and a basis $B$ of $A$ are given. Then, the following linear program is an equivalent linear program in canonical form for the basis $B$,
$$\max\hspace{1em}z(x)=\vec{y}^{T}\vec{b}+\bar{z}+(\vec{c}^{T}-\vec{y}^{T}A)\vec{x}
 $$subject to $$A_{B}^{-1}A\vec{x}=A_{B}^{-1}\vec{b}$$$$\vec{x}\geq\vec{0}$$where $\vec{y}=A_B^{-T}\vec{c}_B$.
Apparently, in this case "basis" means a set of columns in a vector which are linearly independent (rather than anything doing with spanning a vectorspace). $M_B$ denotes an ordered matrix of the columns of $M$ which are members of $B$.
My main trouble is two points:

What on earth is $A_B^{-T}$?
Why is $\vec{c}^{T}-\vec{y}^{T}A$ well defined? It seems very possible for $y$ and $c$ to have different lengths.
The book did not give a good proof of this, just a worked example with real numbers that happens to fit this pattern. Is there an approachable resource I can use to understand optimization of linear models better? Googling only gives resources way above my head, and the textbook for our course is badly written.
Answer:
$A_B^{-T}$ is a shorthand for $(A_B^T)^{-1}$ or equivalently, $(A_B^{-1})^T$.
Yes, $\vec{y}$ and $\vec{c}$ may have different lengths, but $\vec{c}^{T}$ and $\vec{y}^{T}A$ have identical lengths and so one can calculate their difference. For instance, you can compute $(1,2)-(3,4,5)\pmatrix{1&2\\ 3&4\\ 5&6}$ although $(1,2)$ is a 2-vector and $(3,4,5)$ is a 3-vector.
Multiplying $A_{B}^{-1}A\vec{x}=A_{B}^{-1}\vec{b}$ by $A_B$ on both sides, the constraint is equivalent to $A\vec{x}=\vec{b}$. Hence the new linear program has the same constraints as the old one. In addition,
\begin{align*}
\vec{y}^{T}\vec{b}+\bar{z}+(\vec{c}^{T}-\vec{y}^{T}A)\vec{x}
&=\vec{y}^{T}(\vec{b}-A\vec{x})+\bar{z}+\vec{c}^{T}\vec{x}\\
\end{align*}
Under the constraint $A\vec{x}=\vec{b}$, we have $\vec{y}^{T}(\vec{b}-A\vec{x})=0$ and the objective function in the new linear program is equal to the old one. Hence the two linear programs are equivalent.
Comment: But can't $\vec{y}$ be of the wrong dimension to multiply by $A$? After all, it is formed with $A_B$, which has different dimensions from $A$.


@Enumerated(EnumType.STRING) Hibernate JPA

Question: Tenho o seguinte campo classificacao em uma tabela.
Esse campo é preenchido em outro lugar e é preenchido com, somente, 'P' ou 'N', acrônimos para Positivo e Negativo.
Criei então o enum Java.
Classificacao.java
public enum Classificacao {
    POSITIVO('P'), NEGATIVO('N');

    private char classificacao;

    Classificacao(char classificacao) {
        this.classificacao = classificacao;
    }

    public char getClassificacao() {
        return classificacao;
    }
}

Na minha entidade, eu tenho o atributo:
@Enumerated(EnumType.STRING)
@Convert(converter = ClassificacaoEnumConverter.class)
@Column(name = "classificacao", length = 1)
private Classificacao classificacao;

Quando tento listar essa tabela, a seguinte exception é lançada:
java.lang.IllegalArgumentException: Unknown name value [N] for enum class [br.com.jpalab.enums.Classificacao]

Entendo o porque do erro, ele procura o valor N, sendo que só existe POSTIVO e NEGATIVO, mas como eu poderia resolver esse problema?
Criei esse Converter
@Converter
public class ClassificacaoEnumConverter implements AttributeConverter<Classificacao, String> {

    @Override
    public String convertToDatabaseColumn(Classificacao classificacao) {
        return String.valueOf(classificacao.getClassificacao());
    }

    @Override
    public Classificacao convertToEntityAttribute(String classificacaoFromDb) {
        if (classificacao == null) return null;
        switch (classificacaoFromDb) {
            case "P":
                return Classificacao.POSITIVO;
            case "N":
                return Classificacao.NEGATIVO;
        }

        throw new IllegalStateException();
    }
}

Comment: O problema está descrito nessa documentação. https://javaee.github.io/javaee-spec/javadocs/javax/persistence/Converter.html (...)"Note that Id attributes, version attributes, relationship attributes, and attributes explicitly annotated as Enumerated or Temporal (or designated as such via XML) will not be converted." (...)
Answer: Tente usar um Converter com um AttributeConverter:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

public enum Classificacao {
    POSITIVO('P'), NEGATIVO('N');

    private final char classificacao;

    Classificacao(char classificacao) {
        this.classificacao = classificacao;
    }

    public char getClassificacao() {
        return classificacao;
    }

    @Converter(autoApply = true)
    public static class Mapeador implements AttributeConverter<Classificacao, String> {

        @Override
        public String convertToDatabaseColumn(Classificacao x) {
            return String.valueOf(x.getClassificacao());
        }

        @Override
        public Classificacao convertToEntityAttribute(String y) {
            if (y == null) return null;
            if ("P".equals(y)) return POSITIVO;
            if ("N".equals(y)) return NEGATIVO;
            throw new IllegalStateException("Valor inválido: " + y);
        }
    }
}

import javax.persistence.Convert;

// ...

    //@Enumerated(EnumType.STRING)
    @Convert(converter = Classificacao.Mapeador.class)
    @Column(name = "classificacao", length = 1)
    private Classificacao classificacao;

Observe que o @Enumerated foi retirado do mapeamento.
Comment: Sem o converter não deveria ser o suficiente? Ao menos para JPA é, iirc.
Comment: @GustavoCinque Daí o `name()` de cada elemento do `enum` teria que ser persistido. Ou seja, ao invés de ser apenas `P` e `N` no banco de dados, teria que ser `POSITIVO` e `NEGATIVO`.
Comment: True, só depois que comentei que percebi que havia diferença no que o autor queria como nome de enum e o que estava indo à banco.
Comment: Já tentei usar Converter, ele continua lançando a **mesma** exception
Comment: Foi mais rápido do que eu :). Alternativamente podemos criar uma tabela `CLASSIFICACAO` com `ID` e `NOME`. Então podemos criar uma FK na tabela que usa a *enum* referenciando `CLASSIFICACAO.CLASSIFICAO_ID`  e mapear com `@Column(name="CLASSIFICAO_ID")
@Enumerated(EnumType.ORDINAL)`.  A vantagem é que se a *enum* mudar de alguma forma (e.g., se você renomear ou adicionar valores) é bem mais fácil de fazer a mudança, apesar disso criar problemas se você reordenar os membros da *enum* somente do lado do Java.
Comment: @HenriqueSantiago Tentou o `@Converter(autoApply = true)`?
Comment: @VictorStafusa sim, inclusive, eu coloquei um log e debuguei, os métodos da interface AtributteConverter não estão nem sendo chamados.
Comment: o `autoapply = true` é pra quando você quiser fazer isso pra todos os atributos que tenha Classificacao, mesmo setando o converter na anotação @Convert, ou seja, sendo redundante, não dá certo
Comment: @HenriqueSantiago Qual é a versão do seu JPA? E do hibernate?
Comment: `5.2.10.Final`
Comment: só tenho essa dependência, não tenho dependência do jpa
Comment: retirei a anotação de `@Enumerated` e funcionou.
Comment: --' :( :D --' :( :D
Comment: @HenriqueSantiago KKKKKKK - Ou seja, tem que ser o Converter sem o Enumerated.
Comment: @HenriqueSantiago Resposta editada.
Comment: exato, puts! kkkkkkk


Bootstrapping a sample with unequal selection probabilities

Question: I want to "blow up" a sample, taken with replacement, for which I know the overall sampling probability $\pi_i$ for each item $i$. Is it valid to use bootstrapping and apply inverse probability weighting during the selection (as in the Horvitz-Thompson estimator: weight each item with $1/\pi_i$), or are there any pitfalls? A quick search on Google suggests that this hasn't been fully investigated yet, and the boot package in R allows weights but does not comment on where they are supposed to come from.
The purpose of "blowing up" is, among others, to be able to resample with uniform probability from the blown-up population.
Comment: (1) Was your sample obtained with or without replacement?  (2) Selecting items "with probability $1/\pi_i$" won't work (and is not part of the H-T estimator anyway), because obviously--since $\pi_i \le 1$--these reciprocals exceed unity.
Comment: @whuber: Thank you. (1) For now, let's assume it's sampling without replacement. (How does the concept of an overall sampling probability apply to sampling with replacement anyway? Wouldn't it be something like expected sampling count?) (2) Thanks, edited.
Comment: I suspect what you may mean by "inverse probability weighting during the selection" is to use *probability weighting* for the bootstrap according to the relative sizes of the $\pi_i$.
Comment: @whuber: I am not familiar with terminology, and I only have a very rough imagination about what bootstrapping is: Repeated random selection from a sample (with replacement), and appending the selected items to a "new" dataset. If my sample is weighted, then weighted sampling is applied during the bootstrap. And if the weights are derived from selection probabilities, it's inverse probability weighting. At least that's my understanding, please do correct me if I'm wrong here. -- Does the term "weighted bootstrap" apply for my case?
Answer: Did you find a satisfactory answer for this question?
I recently found this reference:
http://www.wseas.us/e-library/conferences/2009/hangzhou/ACACOS/ACACOS21.pdf
but I am pretty sure that the issue must have been investigated before.
While it is easy to justify the use of observation weights (in practice, by weighting observations, you are hoping to use a better estimate of the unknown distribution function F), I would like to find the relevant background.
Comment: Welcome to CrossValidated.  Thank you for attempting to help answer a question.  A small point: your answer could be much improved by briefly summarising the contents of the link as relevant to this question.  This is also important for the longevity of the answers, since if that link ever dies, your answer is useless.
Answer: You can verify that the "weights" parameter in the boot package is operating as importance weights with a simple simulation.
example <- data.frame(
   meas=c(1,1,5,8,10),
   wts=c(10,10,3,2,1)
)

Unweighted mean:
mean(example$meas)
# output = 5

Weighted mean:
sum(example$meas * example$wts) / sum(example$wts)
# output = 2.346154

Now doing this with bootstrapping:
my.avg <- function(data, indices) {
   d <- data[indices,]
   return(mean(d$meas))
}

Unweighted bootstrapped mean:
mean(boot(example, my.avg, 1000)$t)
# output = 4.8908

Weighted bootstrapped mean:
mean(boot(example, my.avg, 1000, weights=example$wts)$t)
# output = 2.3712


Getting all static (interned) strings from a .NET assembly (dll)

Question: I wish to get a list of all strings that are used in a .NET assembly including the "static" values that local variables are set to, parameters passed to methods, fields at set to, etc.
I recall from something I read a long time ago that a .NET assembly contains a tables of all strings it uses (or they can be "interned")– or am I just dreaming?
Using .NET Reflector is a good ideal (thanks thijs), I will also have a look at its API if no one comes up with an already written tool.
(This is so I can write a tool to check we have not missed any strings that should be translated.  I could process the C# source code, however I will then have to cope with
Strings that are split over many lines, etc.)
I have just thought, I wish to exclude strings passed into CodeFlowException(), etc., so this is already getting more complex.
PS: if you can think of a better set of tags, please retag this question.
Comment: No need to write a tool, one already exists....
Comment: I do need a custom tool, as I need to do more processing on the strings once I got them.  However I am more then happy to feed my tool with a list of strings that another tool outputs.
Comment: Try loading your assembly into Reflector, if what reflector sees is good (enough) for you then you can access it using System.Reflection too.
Answer: You can use SysInternals Strings tool to view the strings in executables and object files.
Comment: Using this tool you'll also get stuff like "!This program cannot be run in DOS mode" which is not written in the source but added by the compiler. You'll also get guids and base64 encoded resources if you're unlucky. All that gives you loads of work to separate the crap from the actual strings you need to translate.
Answer: For those who want to extract all user strings from a .NET assembly (.exe or .dll) I wrote a simple utility which can do that (file ExtractExeNetStrings2.zip).
The utility is written in C#.
Comment: Neat, but why does it pick up "hotovo... " but not ".txt.", "Exception: ", "press a key...", "#US", etc. from its own assembled self?
Answer: You should be able to do this using reflection, take a look at this:
http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isliteral.aspx
and
http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.aspx
Comment: Guys, the poster is asking for a way to get the strings so that they can be translated, not enforce naming standards or anything else...
Comment: reflection? why do something the hard way! ;)
Comment: because "strings" also gives all strings that you didn't write yourself? (Such as the names of functions and variables)
Comment: You may not want/need to localize them, but you might want to pull them up anyway to check them for naming standards, quality assurance, f-bombs, etc.
Comment: What about strings that are passed to methods etc.
Comment: My previous comment was referring to "Why do something the hard way"... do it the hard way because the easy way isn't good enough...
Answer: Simple C# utility that extracts all user strings from a .NET assembly (.exe or .dll) by examining bits of a binary file.
The source code from vladob's answer can now be found on github here. The link from the original answer has been broken. vladob gave consent to this repost. Actually I gave consent to me.
Answer: In the end I wrote a very simple C# parser that found the strings in the source code.  This solved the problem I had and let me add "comments" to the strings to help the translators.
The comments were just read from C# comments in a "magic format"
(Sorry the parser is not good enough to allow anyone else to use it, it only just about works on my C# code base)


How is 'distance covered' tracked in football (soccer) at the World Cup and during other official competitions?

Question: In most football leagues, and now the World Cup, distance covered is now a commonly-shared statistic.
Are there trackers in the boots? Do the players have chips implanted in their brains? How is 'distance covered' tracked?

Related: How to find "distance covered" for players during the World Cup?
Comment: I'd expect something like [SportVU](http://www.stats.com/sportvu/sportvu.asp) (which the NBA uses), but I can't find good info.
Answer: Several types of tracking technology exist, and the type used depends upon the the circumstances of the competition.
In training, some teams are now tracking with systems like RedFIR, a German technology comprised of tiny (15 gram) radio transmitters that can be placed in uniforms, footwear or balls, and a network of receivers set up around the field. The system detects events like passes, crosses and goals, plus provides real-time info on player step count, speed, and distance covered. Fraunhofer IIS, the company that makes RedFIR, says that its radio-based system provides a major benefit over other tracking solutions: "its tracking capability is not diminished by obstacles obscuring the line of sight."
But so far FIFA hasn't adopted the technology. This may be because rules changes would be required to implant the transmitters into balls. Also, players haven't been to receptive towards adding microchips to their shoes or shin guards during competition.
FIFA relies on a visual tracking technology called "Matrics" made by the Italian company deltatre to provide data that make up the heat maps, passes completed and distance covered stats made available at the World Cup official site.
From deltatre's webpage:

deltatre can very proudly say to have successfully delivered 3 FIFA World Cups™ since 2002 (South Korea and Japan 2002, Germany 2006 and South Africa 2010) and a total of 1.191 matches including other FIFA Competitions: result of continuous investments in software, hardware, training and people.

Motherboard provides a fascinating look at how "Matrics" is being used at the 2014 World Cup.
Answer: A lot of professional teams these days use ProZone. This is used for Performance Analysis (which 'distance covered' would probably be included), Physiological Monitoring, Player Recruitment and Research/Consultancy. See here for more details on Player Tracking.
Players who wear Adidas boots can also take advantage of the miCoach Speed Cell which covers distance and includes information on sprints and rest periods. I own one of these are they are brilliant, very accurate.
Answer: There are 16 cameras around the field that can track each player's distance traveled within 3% accuracy. Source - WSJ
Answer: They use video processing software that either track the players by jersey color or other features such as their jersey number. They can also place markers on the players before the game and have the software track them from the moment they walk onto the pitch. Finally they can also have a cell on their person that tracks each players relative postion on the pitch.
Once you apply one of these tracking techniques it is pretty easy to get the distance traveled.
video 1
video 2
Comment: This is interesting, but do you have any references to back this up?
Comment: I do not have any official proof of the technique they use for the world cup but I work with computer vision and it was more of an educated guess. The following videos might help understand how the computer vision tracking of players works though.
[video 1](https://www.youtube.com/watch?v=C831bOjtJfg)
[video 2](https://www.youtube.com/watch?v=ZqQIItFAnxg)
Comment: If your answer is just an educated guess, you should say so in the answer itself. People shouldn't have to read the comments to find out such a vital piece of information!


Text output with a label or non-editable text input

Question: I'm a Shiny newbie and I have probably a simple question, but I swear I spent half day reading solutions here and can't find anything close to what I need.
Imaging you have a database with employees ID, name, last name, age.
I need to have in my app a text input that allows the user to enter the ID and to see on the same row the name, last name and age.
The problem I face is that textInput will have a label (say "ID").
All the three other fields, that I need to be on the same row, won't have a label.
So what I would need is either a way to add a label to the three textOutput elements or to display them as textInput with a default value that has to change/behave like an output as soon as a user enters a new ID. But how?
This is my sample code:
library(shiny)
u <- fluidPage(
  titlePanel("Simple Selectable Reactive Function"),
  sidebarLayout(
                sidebarPanel(),
                mainPanel(
                          h2("Results"),
                          fluidRow(column(2,
                                          textInput("input_ID", label = "Cusip 1",
                                                    value = "123")),
                                  column(2,
                                         textOutput(outputId = "output_name")),
                                  column(2,
                                         textOutput(outputId = "output_lastname")),
                                  column(2,
                                         textOutput(outputId = "output_age"))
                                  )
                          )
                )
  )

s <- function(input,output){
        output$output_name <- renderText(
          {             # here is where I will check in a database
            paste("Sample Name")
          })
        output$output_lastname <- renderText(
          {             # here is where I will check in a database
            paste("Sample Last Name")
          })
        output$output_age <- renderText(
          {             # here is where I will check in a database
            paste("Sample Age")
          })
  }
shinyApp(ui=u,server=s)

Perhaps I have to use different widgets?
Thank you
Answer: I updated the code to change the label using an textInput as suggested in the comment. Perhaps it helps to understand exactly what you are looking for.
library(dplyr)
library(shiny)
library(shinyjs)
u <- fluidPage(
  titlePanel("Simple Selectable Reactive Function"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      h2("Results"),
      fluidRow(
        column(2, textInput("input_ID", label = "Cusip 1",value = "123")),
        column(2, textInput("output_name", label = "Firstname") %>% disabled()),
        column(2, textInput("output_lastname", label = "Lastname") %>% disabled()),
        column(2, textInput("output_age", label = "Age") %>% disabled())))))

s <- function(input,output, session){

  observe({
    id <- input$input_ID
    set.seed(id)
    df <- list(firstname = sample(LETTERS, 1), lastname = sample(LETTERS, 1), age = sample(1:100, 1))
    updateTextInput(session, inputId = "output_name", label = df[["firstname"]])
    updateTextInput(session, inputId = "output_lastname", label = df[["lastname"]])
    updateTextInput(session, inputId = "output_age", label = df[["age"]])
  })
}
shinyApp(ui=u,server=s)

Comment: Hi Tom, thanks for your answer but it doesn't solve my problem. If you run your app, where is the label of each output box? how do you know what is the name, last name, and age? That's what I'm trying to achieve. Have a label for the output fields.
Comment: In this case I did not understand your question correctly. Thinking about this, I am not sure how exactly you want the app to behave. If if helps, you might use `textInput` as "output" and update the label with `updateTextInput`. You can also disable it with `shinyjs::disable`.
Comment: that actually does answer my question! So try to visualize 4 fields on the same row. One is an input and 3 are outputs. All 4 fields need a label (ID, Name, Last Name, Age). These labels are all aligned on web page at the same height. Then, all have a value, with the simple difference the first field is an input and the other three are outputs. And again, these values have to be aligned at the same height. If we use textOutput, we won't have their labels. your solution helps. Thanks
Comment: Glad to hear this helped.
Answer: How I create label for my UI is simply adding a h3 tag above each textoutput:
library(shiny)
u <- fluidPage(
  titlePanel("Simple Selectable Reactive Function"),
  sidebarLayout(
                sidebarPanel(),
                mainPanel(
                          h2("Results"),
                          fluidRow(column(2,
                                          textInput("input_ID", label = "Cusip 1",
                                                    value = "123")),
                                  column(2,
                                         h3("First Name: "),
                                         textOutput(outputId = "output_name")),
                                  column(2,
                                         h3("Last Name: "),
                                         textOutput(outputId = "output_lastname")),
                                  column(2,
                                         h3("Age: ),
                                         textOutput(outputId = "output_age"))
                                  )
                          )
                )
  )


Is there a way to implement an organization with many types without duplicating this organization?

Question: I am new at postgresql and database systems.
I have two tables like this:
Organization Table
CREATE TABLE public."Organization"
(
    org_id integer NOT NULL DEFAULT nextval('"Organization_org_id_seq"'::regclass),
    org_name "char" NOT NULL,
    org_description "char" NOT NULL,
    org_email citext COLLATE pg_catalog."default" NOT NULL,
    org_phone "char" NOT NULL,
    bt_id integer,
    CONSTRAINT "Organization_pkey" PRIMARY KEY (org_id),
    CONSTRAINT bt_id1 FOREIGN KEY (bt_id)
        REFERENCES public.business_type (businesstype_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
        NOT VALID
)

Business Type table
CREATE TABLE public.business_type
(
    businesstype_id integer NOT NULL DEFAULT nextval('business_type_businesstype_id_seq'::regclass),
    businesstype_description "char" NOT NULL,
    CONSTRAINT business_type_pkey PRIMARY KEY (businesstype_id)
)

Business type has 4 values. I would like to implement a system in which an organization might have a type between 0 and 4, without the need to duplicate the organization to have a different type. With my schema, for an organization to have two types, I would need to insert the organization two times, having org_id different and bt_id different.
Is there a way to implement a schema where an organization has the same org_id, and multiple bt_id, without the need to insert it multiple times? Further more, I would like for the business type to always be different. For example, an organization might have business type 1, or 1,2,3, but not 1,1.
Answer: You are describing a many-to-many relationship between organizations and business types. To store that relation, you can create a third table:
create table organization_business_type (
    org_id integer
        references organization(org_id)
        on delete cascade,
    businesstype_id integer
        references business_type(businesstype_id)
        on delete cascade,
    primary key (org_id, businesstype_id)
);

This allows 0 to N business types per organization, while forbidding duplicates (the primary key does the latter).
Accordingly, you would need to remove column bt_id from the organization table.
Side note: In Postgres, don't use upper case table or column names: public."Organization" should really be public.organization.