Base 64 from Nodejs using oracledb to query blob data returns empty buffer

Question: blob contents - PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiBmb2N1c2FibGU9ImZhbHNlIj48cGF0aCBkPSJNMTIgMWM2LjA3NCAwIDEwLjk5OSA0LjkyNSAxMC45OTkgMTEgMCA2LjA3NC00LjkyNSAxMC45OTktMTEgMTAuOTk5LTYuMDc0IDAtMTAuOTk5LTQuOTI1LTEwLjk5OS0xMUMxIDUuOTI1IDUuOTI1IDEgMTIgMXptMCAxOC4xNzNhNy4xNzQgNy4xNzQgMCAxMC0uMDAxLTE0LjM0NyA3LjE3NCA3LjE3NCAwIDAwMCAxNC4zNDd6bTAtMy42NTNhMy41MiAzLjUyIDAgMTEwLTcuMDQgMy41MiAzLjUyIDAgMDEwIDcuMDR6IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjwvcGF0aD48L3N2Zz4K
    const chainNumber = req.params.chainNumber;

    try {
        connection.execute(
        `select logo
        from chain_logos
        where chain_id = :1`,
        [chainNumber], {
            outFormat: oracledb.ARRAYBUFFER
        },
        async function(err, result) {
            if (err) {
                console.error(err.message);
                return;
            }
            connection.close();

            const data = result.rows.map(row => ({
                logo: Buffer.from(row[0]).toString('base64'),
                logo2: Buffer.from(row[0], 'base64'),
                logo3: row[0]
            }))
            return res.send({ data });
        });
    } catch (err) {
        console.log('Error: ', err);
        return res.send(`error returning chain logo`);
    }

I'm only seeing an empty buffer returned from the code even though there is blob data:
{"data":[{"logo":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==","logo2":{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},"logo3":{"_readableState":{"objectMode":false,"highWaterMark":16384,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":[],"flowing":null,"ended":false,"endEmitted":false,"reading":false,"sync":true,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"errorEmitted":false,"emitClose":true,"autoDestroy":true,"destroyed":false,"errored":null,"closed":false,"closeEmitted":false,"defaultEncoding":"utf8","awaitDrainWriters":null,"multiAwaitDrain":false,"readingMore":false,"decoder":null,"encoding":null},"_events":{},"_eventsCount":1,"_writableState":{"objectMode":false,"highWaterMark":16384,"finalCalled":false,"needDrain":false,"ending":false,"ended":false,"finished":false,"destroyed":false,"decodeStrings":false,"defaultEncoding":"utf8","length":0,"writing":false,"corked":0,"sync":true,"bufferProcessing":false,"writecb":null,"writelen":0,"afterWriteTickInfo":null,"buffered":[],"bufferedIndex":0,"allBuffers":true,"allNoop":true,"pendingcb":0,"prefinished":false,"errorEmitted":false,"emitClose":true,"autoDestroy":true,"errored":null,"closed":false},"allowHalfOpen":true,"offset":1,"_isActive":false,"_parentObj":{"_rowCache":[],"_processingStarted":false,"_convertedToStream":false,"_allowGetRowCall":false,"_isActive":false,"_parentObj":{"_events":{},"_eventsCount":1,"_dbObjectClasses":{},"_requestQueue":[],"_inProgress":true,"_pool":{"_events":{},"_eventsCount":2,"_queueTimeout":60000,"_queueMax":500,"_enableStatistics":false,"edition":"","events":false,"externalAuth":false,"homogeneous":true,"user":...
Answer: Overall, check the doc and examples.
By default LOBS will return as objects that you can stream from, or can call getData() on.
If your LOBs are 1 GB or less, then you may want to force all LOBs to be returned as Strings or Buffers.  Set these at the top of your code:
oracledb.fetchAsString = [ oracledb.CLOB ];
oracledb.fetchAsBuffer = [ oracledb.BLOB ];

Read the doc on Working with CLOB, NCLOB and BLOB Data for more detail.
The outformat property refers to whether rows are represented by arrays or JS objects.  There is no predefined constant oracledb.ARRAYBUFFER.  Or maybe you added this constant yourself?


Using Convolutional Neural Networks on Board Games

Question: I have troubles with my CNN. The code runs and my network learns something, but the performance is really poor. The goal is to play the game Connect 4. The network therefor receives a numpy array with the size (batch_size, row, cols, 2). The 2 stands for two channels. In channel one there are all places obtained by player one and on the other channels are all places obtained by player two.
It was up now for a few days but still doesn't manage to recognize horizontal lines. It knows four stones vertical is good, and it also stops the opponent from getting four vertically. But there is 0 awareness of playing four diagonally or horizontally. Do I maybe convolute over the wrong axis? This could be an explanation why it only recognizes those...
Here is the CNN part of my code:
    in_x = x = Input((self.observation_space[0], self.observation_space[1], 2))  # stack of own(6x7) and enemy(6x7) field

    x = Conv2D(128, 3, padding="same",
               kernel_regularizer=l2(1e-4))(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation("relu")(x)

    for _ in range(2):
        x = self._build_residual_block(x)

    x = Conv2D(filters=1, kernel_size=1, kernel_regularizer=l2(1e-4))(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation("relu")(x)
    x = Flatten()(x)
    policy_out = Dense(action_space, kernel_regularizer=l2(1e-4), activation="softmax", name="policy_out")(x)

    self.model = Model(in_x, policy_out, name="connect4_model")

    self.optimizer = SGD(lr=1e-2, momentum=0.9)
    self.model.compile(optimizer=self.optimizer, loss='mse')

def _build_residual_block(self, x):
    in_x = x
    x = Conv2D(filters=128, kernel_size=3, padding="same",
               kernel_regularizer=l2(1e-4))(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation("relu")(x)
    x = Conv2D(filters=128, kernel_size=3, padding="same",
               kernel_regularizer=l2(1e-4))(x)
    x = BatchNormalization(axis=1)(x)
    x = Add()([in_x, x])
    x = Activation("relu")(x)
    return x

observation_space is (6,7), action space is (7)
EDIT 1: Just found one first huge mistake. I used the wrong loss. The author defined its own loss. I have used a MSE wich is definitely wrong.
The author from the script I copied the network from has one interesting comment:
import keras.backend as K
...
def objective_function_for_policy(y_true, y_pred):
        # can use categorical_crossentropy??
        return K.sum(-y_true * K.log(y_pred + K.epsilon()), axis=-1)

Is this actually completly the same as categorical_crossentropy? Looks like he wasn't sure either. The epsilon doesn't appear in the crossentropy I know.
Comment: That sure looks like categorical cross entropy to me.  Epsilon is probably just a hack to prevent $log(0)$.
Comment: Ou okay. Thought it's somehow the epsilon used in q-learning (exploration) but it comes from the Keras backend. So I'll replace this part with loss='categorical_crossentropy'
Answer: OP points out in an edit that s/he was not using the same loss function as was used in the reference code. Because OP's code didn't match the reference, it's not surprising that the RL agent found a different result.
Incidentally, this is why I recommend unit tests and careful debugging as a core part of building neural networks specifically and programming generally.
Comment: More information about that can be found in answers to [What to do when my neural network doesn't learn?](https://stats.stackexchange.com/questions/352036/what-should-i-do-when-my-neural-network-doesnt-learn)
Comment: I'm re-running it again right now. It looks like it performs better. I'll give an update if that eliminated the problem.
Comment: Do you might have some information about debugging and unit testing concerning NNs? That's something I don't see trough yet.
Comment: Here is the [link](https://stats.stackexchange.com/questions/352036/what-should-i-do-when-my-neural-network-doesnt-learn) for the question mentioned in the above comment.
Answer: It's difficult to answer this without reproducible code. However, one thing that jumps out is you don't seem to be doing any pooling between convolutions. This might be making it difficult for your network to recognize longer patterns. So for example if you do a 3x3 convolution in the top left of the board, and a 3x3 on the top right, there doesn't seem to be any communication between the two, except through the dense layer. Consider adding a few pooling layers, or changing the padding="valid" in the last few convolutions to incur a contraction of spatial dimensions.
Comment: thats the link to the Github Repo: https://github.com/Zeta36/connect4-alpha-zero
I wrote my own Connect 4 and my own evaluation. I copied just the network from model_connect4.py file
Comment: actually there is one valid convolution anyway. The second Conv2d has no padding parameter, default is valid. The ResNet implementation is same in all implementations i've seen so far. Just checked some of them again.
Comment: oh no thats necessary. in reinforcemnt learning one doesnt add pooling layers. the model structure is already prooven and inspired by alpha go / deepmind. I think its rather a small mistake, typo, swapt indices. Possibly a wrong input vector or something like that.
Comment: @Mr.Sh4nnon: What you're saying makes zero logical sense. This has nothing to do with reinforcement learning, but with the structure of convolutions. Try changing the last few convolution blocks to have `padding="valid"` to contract dimensions by 2. This will at least allow long-range convolution outputs to be processed, in lieu of pooling. For example: https://github.com/suragnair/alpha-zero-general/blob/master/othello/keras/OthelloNNet.py
Comment: I suggest reading the deepmind atari paper. Pooling isn't used  there since positional information is crucial. Droupot is also often better not used due to the tricky RL optimization environment... I wish I had just asked this in the Stackoverflow section
Comment: @Mr.Sh4nnon: You need SOME FORM of dimensional contraction to link far away convolutions. This can be done EITHER with pooling OR by a consequence of non-padding your convolution input.
Comment: Ok, the problem is just I copied this from a famous alpha go addaption. And I mean it. I copied exactly this way. And I dont know who do trust now. Sinde running the source I got it from has outstanding performance...
Comment: Source link please?
Answer: The problem was as discovered in EDIT 1 the use of MSE. Theoretically MSE might would work if trained for 1000 of hours, but cross-entropy performs much better.
After training my network over night it's still a rather dumb player. However, it now has an awareness of horizontal and vertical lines. At least sometimes...
In my implementation only the policy is part of the network. In the implementation I copied the network from, the policy's values are calculated too, which makes it smarter in the end. I have to do some more fine tuning to get similar performance.


AutoSizeTextType uniform crops my textview bottom part

Question: I have such code for textview:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="sometextsometextsometextsometextsometextsometextsometextsometextsometext"
android:textStyle="bold"
app:autoSizeMaxTextSize="30sp"
app:autoSizeMinTextSize="18sp"
app:autoSizeStepGranularity="2sp"
app:autoSizeTextType="uniform"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>

and it looks on the design:

after some tests I found that when I remove app:autoSizeTextType="uniform" or change it to none my text can fill TextView without cropping. But as I know app:autoSizeTextType="none" turns off responsive text size. Maybe I did any mistake in my xml what causes such problem?
Comment: use android:autoSizeTextType="uniform" instead of app:autoSizeTextType="uniform" that should fix your issue.
Comment: @Parmesh, it is bad solution because in such case as I see all test responsivity is turned off
Comment: This issue is happening because of android:layout_height="wrap_content", its better to have some fixed height or more height. I will suggest you to use horizontal guideline and constraint this textview with that guideline (incase you can't give fixed height for this textview).
Comment: can you post any possible solution for this problem for better understanding pls?
Answer: There are multiple solutions of this problem but below solution might be useful for you.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:id="@+id/t1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:autoSizeMinTextSize="18sp"
    android:padding="10dp"
    android:minLines="2"
android:text="sometextsometextsometextsometextsometextsometextsometext"
    android:background="#faa"
    android:textStyle="bold"
    app:autoSizeMaxTextSize="30sp"
    app:autoSizeTextType="uniform"
    app:autoSizeStepGranularity="2sp"
    app:layout_constraintBottom_toTopOf="@id/horizontalGuideline"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/horizontalGuideline"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.1"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Here you can change the Guideline percent according to your requirement, in this example I have kept 0.1 which is 10% from top of the page.
I hope it will resolve your issue.
Github code link: https://github.com/parmeshtoyou/StackOverflow/blob/master/app/src/main/res/layout/activity_main2.xml


Como mostrar apenas linhas que aparecem mais de x vezes. (shell script)

Question: Estou analisando um arquivo de log e eu queria filtrar apenas linhas que aparecem mais de 10 vezes dentro do arquivo. So que eu não estou conseguindo achar uma forma de fazer esse filtro.
Answer: Você usará do seguinte comando:
sort SeuArquivo | uniq -c

Caso ainda deseje ordenar pela quantidade de ocorrências utilize:
sort SeuArquivo | uniq -c | sort -nr

Comment: +1 eventualmente `  ... | awk '$1 > 10 {print $2}`


How i can serialized data to json with drf serializer

Question: I have data models like:
from django.db import models

class Student(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):
        return self.first_name + ' ' + self.last_name

class Course(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)

    def __str__(self):
        return self.name

class CourseParticipant(models.Model):
    course = models.ForeignKey(Course, related_name='courses', on_delete=None)
    student = models.ForeignKey(Student, related_name='students', on_delete=None)
    completed = models.BooleanField(null=True, default=False)

    def __str__(self):
        return self.course

I have some serializer like:
class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ('name', 'end_date', 'start_date')

I need return data in json like:
{
    "courses": [
        {
            "name": "Math",
            "end_date": "2019-06-26",
            "start_date": "2019-06-26",
            "participant_students_count: 10
        }
    ]
}

How I can get "participant_students_count" and return its data in json with other fields.
Thanks for help!
Answer: You can use SerializerMethodField of DRF serializer field. Also, see about how to follow Backward access of Foreign key relationship.
from rest_framework import serializers

class CourseSerializer(serializers.ModelSerializer):
    participant_students_count = serializers.SerializerMethodField()
    class Meta:
        model = Course
        fields = ('name', 'end_date', 'start_date', 'participant_students_count')

    def get_participant_students_count(self, obj):
        return obj.courseparticipant_set.count()

Answer: class CourseSerializer(serializers.ModelSerializer):
    participant_students_count = serializers.SerializerMethodField()

    def get_participant_students_count(self, obj):
        return CourseParticipant.objects.filter(course=obj).count()

    class Meta:
        model = Course
        fields = ('name', 'end_date', 'start_date', 'participant_students_count')


What is the biggest sports stadium in the world?

Question: Which sports stadium (meaning any building designed to host sporting events) in the world, is the largest and who plays there? I'm thinking the largest as in the amount of people it can hold, but if you can come up with something different to go by, that's fine.
I am including any stadium that was made or designed to house any sort of sporting event. Motor racing is considered a sport so that is valid.
I think I read somewhere that the University of Michigan Wolverines have the largest capacity stadium in the USA. Is that true? And if so are there any larger than that?
Answer: If you refer to the most people attended in a sport match:

[Indianapolis Motor Speedway][2] (motor racing venue) is the largest in the world with an capacity of 400,000 located at Speedway, Indiana, United States (although it has a seating capacity of 257,325 it has a infield seating that raises the capacity to an approximate 400,000).

You can read about more sporting venues with a highest attendance at the following Wikipedia list.
Answer: This is pretty general question, but Wikipedia has a great list of capacity for sports stadiums around the world.
This articles notes that Rungrado May Day Stadium in Pyongyang, North Korea has the largest capacity in the world at 150,000. The second largest, Salt Lake Stadium in Kolkata, India, has 30,000 less capcaity. The Korea DPR national football team plays in Rungrado May Day Stadium.
In the United States, it is Michigan Stadium in Ann Arbor, Michigan. This is also the third largest stadium in the world. Michigan Stadium, sometimes referred to as "The Big House," hosts the University of Michigan Wolverines football team and has a capacity of 109,901.
Comment: The UMich Big House seats something like 124,000 for hockey which is beyond ridiculous.  When I was working in Ann Arbor I wandered around the stadium and it is truly monstrous!
Answer: The largest sports stadium is the Strahov Stadium in Prague with a capacity of 220,000. Now closed.
http://en.wikipedia.org/wiki/Strahov_Stadium
Comment: Touche. I was dumb enough to only look at stadiums that are currently used by sports teams. Nice job.


Stop watch app in swift 11 (New to the coding world)

Question: I'm getting 4 different error messages.

Type 'StopWatchViewController' does not conform to protocol 'UITableViewDataSource'
In declaration of 'StopWatchViewController'
Use of unresolved identifier 'UITabelViewCell'
Use of unresolved identifier 'UITabelViewCellStyle'

//
import UIKit

class StopWatchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var laps: [String] = []

    var timer = Timer()
    var minutes: Int = 0
    var seconds: Int = 0
    var fractions: Int = 0

    var stopwatchString: String = ""

    var startStopWatch: Bool = true
    var addLap: Bool = false

    @IBOutlet weak var stopWatchLabel: UILabel!
    @IBOutlet weak var lapsTableView: UITableView!
    @IBOutlet weak var startStopButton: UIButton!
    @IBOutlet weak var lapResetButton: UIButton!

    @IBAction func startStop(_ sender: AnyObject) {

        if startStopWatch == true {

            timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: Selector(("updateStopWatch")), userInfo: nil, repeats: true)
            startStopWatch = false

            addLap = true

        }else {

            timer.invalidate()
            startStopWatch = true

            addLap = false
        }
    }

    @IBAction func lapReset(_ sender: AnyObject) {
    }
   if addLap == true {

    laps.insert(stopwatchString, atIndex: 0)
    lapsTableView.reloadData()

    }else {

    addLap = false

    fractions = 0
    seconds = 0
    minutes = 0

    stopwatchString = "00:00.00"
    stopwatchLabel.text = stopwatchString

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        stopWatchLabel.text = "00:00.00"

        // Do any additional setup after loading the view.
    }

  override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func updateStopwatch() {

        fractions += 1
        if fractions == 100 {

            seconds += 1
            fractions = 0

        }

        if seconds == 60 {

            minutes += 1
            seconds = 0
        }

        let fractionsString = fractions > 9 ? "\(fractions)" : "0\(fractions)"
        let secondsString = seconds > 9 ? "\(seconds)" : "\(seconds)"
        let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"

        stopwatchString = "\(minutesString):\(secondsString).\(fractionsString)"
        stopWatchLabel.text = stopwatchString
    }

    //Table View Methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return laps.count
    }

    func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = UITabelViewCell(style: UITabelViewCellStyle.Value1, reuseIdentifier: "Cell")

        cell.backgroundColor = self.view.backgroundColor
        cell.textLabel.text = "Lap \(indexPath.row)"
        cell.detailTextLabel?.text = laps[indexPath.row]

        return cell

    }

}

Answer:
Your method cellForRow does not have the correct signature, it should be func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
UITabelViewCell should be spelt UITableViewCell
UITabelViewCellStyle should be spelt UITableViewCellStyle

You should check your spelling, most of the time errors are related to it.


Model building, p value of GLM for whole model?

Question: I have three GLM models (poisson distribution) that each have different factors but the same response variable. I plan to compare the fit of the models using AIC, but first I want to see if any of the models are significant according to a p value. Is is possible to get a p value for a whole model w/glm? Each model has 1 significant factor and one or two non-significant factors, but I was told to leave these non-significant factors in the models instead of removing them with sinful backwards stepwise regression.
Comment: What software are you using?
Comment: You must subscribe to Frank Harrell's philosophy and arguments if you think stepwise regression is sinful!
Comment: I'm using R. I just learned about the sins of stepwise regression....my original analysis and two stats classes were pro-stepwise
Answer: There are "whole model" tests such as likelihood ratio, Wald, and the score test. These are described in detail in Frank Harrell's book.
You might also consider evaluating each model using $R^2$ and each model's predictive accuracy in cross-validation. For the latter, it's helpful to use the same cross-validation "folds" with each of your models.
Answer: Yes.  Many GLMs can be tested using a likelihood ratio test comparing the model with a restricted model that has only no covariates.
Answer: Yes.
Likelihood ratio test can be used where you test "smaller" model versus "larger". If test statistic is significant it means that residual/deviance variation will increase if smaller model is used.
-Analyst
Comment: The significance of the test statistic does not determine whether the residual deviance will increase for a smaller model (that always happens); further, please don't sign your posts; your name is given in the block on the right.


How to use not in in drupal views 3

Question: I'm using Drupal 7 with views 3.
I need a list of students who have due payments in a view. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in other table. How can I have this is views 3
EDIT Better explanation of query
I am using views 3 to get a list of students who have due payments. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in fees paid table. How can I have this is views 3.
My Table structure is:
I have a table structure for fee details as
fid
name
description
currency
fee
instalments
created

This fee schedule has N no of instalments and storing in a cross ref table as
iid
fid
instalment_no
amount
payable_by

This fee schedule has associated students and are storing in a cross ref table as
fid
uid

The table structure for paid students who has paid fees.
pid      Payment ID serial
fid      Fees ID details
iid      Instalment No
uid      Student who has paid the fees
paid_on  Payment date

Thanks in advance for your help.
Comment: Insufficient details provided.
Answer: My suggestion: You could make this a great deal easier for yourself if "Has payed" a field on the User entity instead.
Answer to your question: You need to expose the custom table to Views, by telling Views that it exists and what type of data there is in it. The canonical way of doing that is with hook_views_data, although the Data module claims to be able to do this automatically.
Once you have the data in Views, you create a View based on "User", and add a "Filter" to remove all users in the "Payed" table.
Comment: Thanks Letharion, I can not make a new field for "Has Payed" as you can see in updated question that I have N no of instalments in one payment schdule. So my logic will be to show the users with instalment due which are not in "Payments" table. In filter critaria, how can I filter records not in other table?
Comment: Not sure why you couldn't use Field API for that. Also don't knwo which part of the rest of my answer that requires clarification. :)
Comment: I have multiple instalments per payment schdule and student. I installed the data module, but there is no documentation available for the usage.

How to use not in in drupal views 3


Uncaught TypeError: $(...).anotherfunc is not a function

Question: flip.js effect is working and console.log inside flip:done is also working but "anotherfunc" called inside flip:done is not working. please help.
function anotherfunc( ) {
    console.log("its anotherfunc");
}

jQuery(document).ready(function($) {

//it is working here but not inside flip:done
anotherfunc();

$(".card").flip({
    trigger:  'hover',
    speed : 1000
});

$(".card").on('flip:done',function(  ){

  // this is also working
  console.log('from inside flip:done');

  // this is also working
  console.log( $(this) );

  // this is saying "is not a function"
  $(this).anotherfunc();

});

});//on laod

Comment: that is because `$(this)` is referring to `$(".card").on('flip:done',function(  ){..}` Look into the javascript scope and closure
Answer: You sould either call it as
anotherfunc($(this));

or declare it like:
(function ($) {
     $.fn.anotherfunc = function () {
           // some code
     }
})(jQuery);

Then you can use it like:
$(this).anotherfunc();

Have a look at this Demo: https://jsfiddle.net/f8w14sbk/
Comment: Thanks it is working by declaring like this. $.fn.anotherfunc = function () {
           // some code
     }
Answer: Yes,  anotherfunc is a function, but there is no jQuery.anotherfunc() to call on $(this)
anotherfunc() is declared on top scope, if you want to pass an object to it do
 function anotherfunc(myobject) {
 ....
}

and call it for $(this)
anotherfunc($(this));

Make sure to clear out if myobject is allowed to be null
Comment: Thanks it is working by declaring like this. $.fn.anotherfunc = function () {
           // some code
     }
Comment: Great. You should choose and vote then for Ashkan's answer.


Smallest sample size for true proportion estimation (Binomial distribution with 1 found defective unit)

Question: Suppose that we allow only 1 defective unit in the control sample. What is the smallest sample it should be in order to conclude that my true defective proportion of the population is smaller than 0.5% (with 95% confidence level).
I have tried to solve this problem using the binom.confint function in R. Since my defective rate is too small (near 0), I have calculate the confidence interval of the true proportion with the Wilson interval. Then I look for the sample size who gives the nearest upper limit from the 0.5% value. The sample size that I found is 1130 since the upper limit of the IC is 0.4999%. So I can conclude that if I found 1 defective unit in a sample of 1130 units, my true defective proportion should be lower than 0.5% (with 5% error)
binom.confint(x = 1, n = 1130)

Is this a good approach? Do you have other suggestion?
Thank you
Answer: This is a very good approximate approach.  For exact inference you can reference the CDF of a binomial distribution with $p=0.005$ and identify the $n$ such that the probability of observing $1$ or fewer events is $2.5\%$.  This approach yields an $n$ of 1,113.  The resulting two-sided equal-tailed $95\%$ confidence interval from inverting the binomial CDF would be would be $(0.00002275, 0.00499)$.
Answer: It sounds like you will want a one-sided confidence interval since you are interested in testing whether the proportion is less than 0.5%. The binom.confint function uses a two-sided interval.
The upper limit for an exact one-sided 95% interval is equal to the 95% quantile of a $\text{Beta}(x + 1, n - x)$ random variable, so you need to find $n$ such that qbeta(0.95, 2, n-1) $\leq 0.005$. This is the case when $n \geq  947$.


If $\dfrac{bx-ay}{cy-az}=\dfrac{cx-az}{by-ax}=\dfrac{z+y}{x+z}$, then the ratio is equal to $\dfrac{x}{y}$, unless $b+c=0$

Question: If $\dfrac{bx-ay}{cy-az}=\dfrac{cx-az}{by-ax}=\dfrac{z+y}{x+z}$, then will each of these fractions be equal to $\dfrac{x}{y}$, unless $b+c=0$
$\Rightarrow\dfrac{bx-ay}{cy-az}=\dfrac{cx-az}{by-ax}=\dfrac{z+y}{x+z}=k$
$$bx-ay=(cy-az)k$$
$$cx-az=(by-ax)k $$
$$z+y=(x+z)k$$
Then I don't know how to proceed. If I set $k=\dfrac{x}{y}$ then the equations become really messy, so it doesn't seem like this is the way. Besides the question asks to show the ratios equal $\dfrac{x}{y}$, not assume it. Thanks for the help.
Answer: If $a=0$, it gives
$$\dfrac{bx}{cy}=\dfrac{cx}{by}=\dfrac{z+y}{x+z}\Rightarrow b^2=c^2$$
Since $b+c\neq0$, we get $b=c$, done.
If $a\neq0$

$$bx-ay=(cy-az)k\tag{1}$$
$$cx-az=(by-ax)k\tag{2} $$
$$z+y=(x+z)k\tag{3}$$

$(1)+(2)+a\cdot(3)$, we get
$$(b+c)x=(b+c)yk$$
Since $b+c\neq0$, we get $x=yk$, hence $k=\frac xy$, done.
Comment: $b^2=c^2\Longleftrightarrow (b+c)(b-c)=0$
Comment: Thanks for your response. I follow you to $b^2=c^2$. But then how do you know $b+c\neq0$? And why do I need to know that before just squaring both sides and getting $b=c$? For the second part, how do you know to operate doing $(1)+(2)+a\cdot(3)$? And why do you also know here $b+c\neq0$?
Comment: you said "unless" $b+c=0$
Comment: Why is it necessary to set $a=0$ in the beginning and finding out $b=c$? Can't we just skip to doing the three equations? Thanks.
Comment: Yes, you can, this is just my personal habit to discuss special cases separately.
Comment: I understand in $(b+c)x=(b+c)yk$ that $b+c\neq0$ is a necessary condition (Otherwise it will be $0=0$. How does $b+c\neq0$ affect $b^2=c^2$? I don't understand this part because I would just square root it without thinking about $b+c\neq0$. Thanks.


How to migrate data from MongoDB to SQL-Server?

Question: I searched around I found that there are ways to transfer/sync data from sql-server to mongodb.
I also know that Mongodb contains collections instead of table and the data is stored differently.
I want to know whether it is possible to move data from mongodb to sql-server. If yes, then how and what are the tools/topics should I use?
Comment: How deep are the nesting layers in your JSON documents?  Is your data flat?

Is your data actually JSON or is in binary + metadata stored in GridFS?

What kind of queries do you want to run?  Structured, primary key retrieval, joins, queries from BI tools that don't support MongoDB?

All these points will help people answer.
Answer: Of course it's possible, but you will need to find a way to force the flexibility of a document db like MongoDB into a RDBMS like SQL Server.
It means that you need to define how you want to handle missing fields (will it be a NULL in the db column? or a default value?) and other things that usually don't fit well in a relational database.
Said do, you can use an ETL tool able to connect to both databases, SSIS can be an example if you want to stay in the MicroSoft world (you can check this Importing MongoDB Data Using SSIS 2012 to have an idea) or you can go for an open source tool like Talend Big Data Integration which has a connector to MongoDB (and of course to SQL Server).
Answer: There is no way to directly move data from MongoDB to SQL Server. Because MongoDB data is non-relational, any such movement must involve defining a target relational data model in SQL Server, and then developing a transformation that can take the data in MongoDB and transform it into the target data model.
Most ETL tools such as Kettle or Talend can help you with this process, or if you're a glutton for punishment, you can just write gobs of code.
Keep in mind that if you need this transformation process to be online, or applied more than once, you may need to tweak it for any small changes in the structure or types of the data stored in MongoDB. As an example, if a developer adds a new field to a document inside a collection, your ETL process will need rethinking (possibly new data model, new transformation process, etc.).
If you are not sold on SQL Server, I'd suggest you consider Postgres, because there is a widely-used open source tool called MoSQL that has been developed expressly for the purpose of syncing a Postgres database with a MongoDB database. It's primarily used for reporting purposes (getting data out of MongoDB and into an RDBMS so one can layer analytical or reporting tools on top).
MoSQL enjoys wide adoption and is well supported, and for badly tortured data, you always have the option of using the Postgres JSON data type, which is not supported by any analytics or reporting tools, but at least allows you to directly query the data in Postgres. Also, and now my own personal bias is showing through, Postgres is 100% open source, while SQL Server is 100% closed source. :-)
Finally, if you are only extracting the data from MongoDB to make analytics or reporting easier, you should consider SlamData, an open source project I started last year that makes it possible to execute ANSI SQL on MongoDB, using 100% in-database execution (it's basically a SQL-to-MongoDB API compiler). Most people using the project seem to be using it for analytics or reporting use cases. The advantage is that it works with the data as it is, so you don't have to perform ETL, and of course it's always up to date because it runs directly on MongoDB. A disadvantage is that no one has yet built an ODBC / JDBC driver for it, so you can't directly connect BI tools to SlamData.
Good luck!
Comment: SQL Server has supported non-relational data for decades. It's not always the best choice, but you can easily slam the data into JSON columns (really `nVarChar(max)`) and, if using older versions, use C# extensions to add JSON comprehension support.
Answer: There is a tool provided by MongoDB called mongoexport and it's capable of exporting csv files. These csv files can be easily imported into MySQL. Good luck!
Comment: I exported the mongodb collection with fields but the transferring data to Sql-server using ssis needs a lot of tuning. I will update if i am successful.
Comment: I think it export one collection at a time. Is it possible to export all collections  into csv with one command?


Non-statistically significant effect of the instrument in the reduced form of the 2SLS

Question: I am using a 2SLS, with two endogenous variables and two instruments.
I conduct the Under- and the Weak-identification tests; results from these tests suggest that my instruments are not weak.
Moreover, in the two first stages (i.e. regression of the endogenous variable on the instrument), the instruments have always a statistically significant effect on the endogenous variable.
Finally, although I cannot conduct that over-identification test (i.e. I have as many endogenous variables as instruments), my arguments on the validity of the two instruments are solid (grounded on the literature).
In the second stage, the two predicted variables from the first stage have a statistically significant effect on the outcome.
It seems like things are working just fine. However, my question is this:
In the reduced form (i.e. regression of the outcome variable on the instruments), one of the two instruments does not have a statistically significant effect on the outcome variable. What does that imply?
It seems like displaying the results from the reduced form of the 2SLS might be needed to show that you are not "inventing" the results (my own interpretation of the third answer here) and thus just to reassure the referee (in the case you are working to revise a paper submitted to a journal). I cannot evaluate this answer, but might it hide some truth? (i.e. there might be no technical reason nowadays)
I have read somewhere that the reduced form might be used as an additional indirect way to test whether the instruments are weak; see section 11 of this document or see this short article. However, I am not sure I fully get the content of these two sources just now.
[Reduced form is used for the wald estimate when you have one endogenous variable and one instrument, but it is not my case...so I am wondering whether I might not even report the reduced form in the table with the 2sls output]
Comment: "...first stages (i.e. regression of the instrument on the endogenous variable)..."---the first stage regression is the other way around, i.e. original endogenous regressors are regressed on the IV's. In any case, if 2SLS gives significant results but reduced form regression does not, it indicates the instruments are weak.
Comment: "...why results from [reduced form] tests do not give evidence of these being weak instruments..."---relevance or weakness of instruments is a statement about the relationship between $x$ and $z$. It would be pretty strange to test for weakness by regressing $y$ on $z$. The first stage regression is a much more direct way to see that. The reduced form regression gives you an F-test for $x$ when $x$ is endogenous and you know the instrument is weak.
Comment: Ya, that's a typo, I have corrected them (thank you for that! I hope the correction was not sloppy as I am using the phone). What I do not understand is why results from tests do not give evidence of these being weak instruments (kleibergen-paap rk walk f statistic are always high)
Comment: I find it stil strange that the test above does not provide evidence of weakness, and the first stages are all ok; however, one of the two instruments has no statistically sign association with the outcome in the reduced form.
Answer: "...first stages are all ok" is usually decided by some empirical rule of thumb that's more or less arbitrary.

In the reduced form (i.e. regression of the outcome variable on the
instruments), one of the two instruments does not have a statistically
significant effect on the outcome variable. What does that imply?

It need not imply the instrument is weak (which seems to be the conclusion you're driving at).
One possibility is that the first stage regression gives an $R^2$ that's not large (but a sufficiently large F-statistic to tell you "...ok"). This can easily happen when, for example, sample size is large. So there is enough variation in the instrument that is not explained by the endogenous regressor. As a result, in the reduced form regression, this unrelated variation washes out the significance you see in the second stage. (In the second stage, you're regressing on the part of the instrument that's fitted by the regressor. In the reduced form,  the part of the instrument that's not explained by the regressor also plays a role. )
In any case, same example shows that non-significance in reduced form regression should not be taken as a sufficient condition for weak instrument. Instead, it's probably more appropriate to invoke reduced form when it's known that the instrument is weak.


Quando faço uma requisição na minha API Rest com Spring boot, ela está vindo com um item a mais

Question: Já debuguei e o resultado tá saindo uma lista correta, porém quando faço a requisição no Postman, vem um item a mais. Parece um contador. Alguém pode me dizer oq é isso e como tirar?

Esse é meu controller.
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.uezohub.backend.domain.models.Curso;
import com.uezohub.backend.domain.service.CursoService;

@RestController
@RequestMapping("/curso")
public class CursoResource {

    @Autowired
    private CursoService cursoService;

    @GetMapping
    public List<Curso> buscarCursos() {
        return cursoService.buscarTodos();
    }

    @PostMapping
    public ResponseEntity<Curso> salvarCurso(@RequestBody Curso curso, HttpServletResponse response) {
        Curso cursoSalvo = cursoService.salvar(curso);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri()
                    .path("/{id}").buildAndExpand(cursoSalvo.getId()).toUri();
        response.setHeader("Location", uri.toASCIIString());

        return ResponseEntity.created(uri).body(cursoSalvo);
    }

    @GetMapping("/{id}")
    public Curso buscarCursoPorId(@PathVariable Long id) {
        return cursoService.buscarPorId(id);
    }
}

Esse é meu modelo
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "curso")
public class Curso {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private boolean ativo;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Long getCurso() {
        return id;
    }
    public void setCurso(Long curso) {
        this.id = curso;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public boolean isAtivo() {
        return ativo;
    }
    public void setAtivo(boolean ativo) {
        this.ativo = ativo;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (ativo ? 1231 : 1237);
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((nome == null) ? 0 : nome.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Curso other = (Curso) obj;
        if (ativo != other.ativo)
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (nome == null) {
            if (other.nome != null)
                return false;
        } else if (!nome.equals(other.nome))
            return false;
        return true;
    }

}

Answer: No seu modelo tem um método getCurso() que retorna o id. Por isso na hora de serializar para JSON ele está imprimindo a chave curso com o mesmo valor do id.
Para ajustar basta remover o método getCurso.
Comment: Po era isso mesmo, muito obrigado !! Não tinha percebido porque olhei os atributos e não olhei os métodos. O framework entende esses métodos como propriedades né ? Não tinha percebido isso, obrigado !!
Comment: Isso, assim como em outros frameworks são usados os métodos `get` da sua classe para ler um objeto. Qualquer método `get` pode ser entendido como uma propriedade da sua classe pelo framework.
Comment: Entendi, muito obrigado !!


How can I remove None values of one list and the equivalent values from another?

Question: I have been trying to solve this problem for a while. What I am trying to do is remove the None values from a list like:
list1 = [2,3,4,None,2,4,5]
I also have other lists that have correlated values to the list1 values (imagine list1 is days and the other two are things that happen in those lists):
list1 = [2,3,4,None,2,4,5]

list2 = ['red','blue','white','red','blue','blue','blue']

I want to remove the None value and also the red from the other list. So I want them to look like:
list1 = [2,3,4,2,4,5]

list2 = ['red','blue','white','blue','blue','blue']

What I have tried is the following:
    for j in array_length(list1):

        if list1[j] is None: #if value is None
            print("Missing values. Omitting day.")
            del list1[j] #deleting that day from all datasets
            del list2[j]

Where array_length is a function I have created to give me an array from 0 to the lenght of the list I am targetting. The above code does not work, as it gives me the following error:
IndexError: list index out of range
What I think is happening is that the indexes are not updating correctly, but I dont know how to solve it or get around it.
Comment: thanks for the edit!
Comment: Are `list1` and `list2` , lists or tuples? change the bracket to square bracket. `list1=[2,3,4,None,2,4,5]`
Answer: The problem is caused because you're deleting items from the list while looping. So when you start the loop the length of the list was 7, but because you deleted one item in the middle, the loop goes out of index in the final stage. Lesson: Don't delete from list while using it in a loop.
But here is a way to do it without causing error
list1 = [2,3,4,None,2,4,5]
list2 = ['red','blue','white','red','blue','blue','blue']

for i, val in enumerate(list1):
  if val is None:
    del list1[i]
    del list2[i]

Comment: It works well, suggested to change `==` to `is` like - `if val is None: `
Comment: @Epsi95 this one doesn't cause a problem. because I'm using enumerate
Answer: You can try zip with all
list1 = (2,3,4,None,2,4,5)

list2 = ('red','blue','white','red','blue','blue','blue')

l = [i for i in zip(list1, list2) if all(i)]

l1 = [i[0] for i in l]
l2 = [i[1] for i in l]

print(l1, l2)

[2, 3, 4, 2, 4, 5]
['red', 'blue', 'white', 'blue', 'blue', 'blue']


How to remove a Views row if field equals value?

Question: In my view I have a made a customised global field that returns a boolean result.
What I now need to do is if this field equals zero then the whole row should be ignored/removed from the view.
The issue here is that I cannot see this field in Filter Criteria to add as a filter.  I have also looked into a programmatical solution but have looked at hook_views_post_render and hook_views_pre_render but cannot see how I can achieve this.
Any help, module suggestions or push in the right direction would be very much welcome.
Answer: I would use a views row template override for this. Do the following in a Development site first.
1) In the view, expand the Advanced options and click on the Theme: Information link. This displays all the available theme template suggestions.
2) Under the heading "Row style output" you will see all the possible template suggestions. Which one you override depends on your needs, but the last listed is the most specific so I would start there. Select it with your cursor and copy the file name.
3) Open this file in your code editor: sites/all/modules/views/theme/views-view-fields.tpl.php
4)Save it as the most-specific suggestion (the value you copied in step 2) and save it to your theme's template directory (e.g., sites/all/themes/yourtheme/templates or sites/all/themes/yourtheme/templates/views)
5) Now you can edit the template (the one we just saved to your theme). You can use a combination of html and PHP to achieve the exact markup and logic you want. Generally it's best practice to not code a lot of logic into your templates (use preprocess functions instead), but simple logic like checking if a field is present or has certain values is fine to include in the template.
There are many different ways to do this, but here is an example (change field_custom_boolean to the machine name of your custom global field ...
 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>
  <?php
  /* if custom field is present and set to 1 */
  if (isset($content['field_custom_boolean']) && $fields['field_custom_boolean'] == '1'): ?>
    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

6) Save file and flush all caches. Now when you check the view Advance:theme information settings, you should see your template override listed in boldtype. When you load your view it should only display rows for records where the custom global field is set to 1.
Good luck.
For more info on Views templates, see:
https://api.drupal.org/api/views/theme%21theme.inc/group/views_templates/7.x-3.x
https://www.drupal.org/docs/7/modules/views
Comment: Hi Anne

Thanks for this.  I've used views templates before but hadn't considered them this time because previously I found issues when trying to use the 'View data export' module to download view data I'd manipulated in templates.  However in this scenario this solution will suffice nicely .
Answer: If I was trying to quickly achieve this frontend, I would use JS/jQuery.
$(".view-name .boolean").each(function() {
    $this = $(this);
    $this.addClass("value-" + parseInt( $this.text() ) );
});

Then, I would just use CSS to hide it:
.value-0 {
  display: none;
}

JSfiddle
Update: It looks like Views has a new filter called the "Global: Combine fields filter". Might be worth checking out.
Comment: This could be a solution only if divulging the data is not an issue.


How to create product bundle or similar to that?

Question: I have a plan to create a e-commerece website for Computer Assembling.
I have exp in Prestatshop and few other CMS (e-commerce) framework.
In that i found Drupal 7 is having the best one like durpalecommerece. So I selected Drupal 7 as CMS framework.
I download few modules ubercart and tried e-commerce module also.
But its not meeting my requirements. My requirement is

Homepage - User can see All default PC set (Monitor, CPU, Keyboard and Mouse) with price.
Select PC, Next page description will display.
Defualt Product piece is 1, but the user can increase more.
Based on the increase Rate will be changed.

Above steps are working fine. Below steps are not working.

Homepage - If user doesn't happy with default PC set, User can build there own PC
Select "Build own PC".
List of Monitor companies and inches will display.
User selects one monitor and click,
It will redirect to CPU Parts.
User will select Mother board, ram, hardisk ... one by one
On click "NEXT" redirect to shopping cart....

How to achive Product bundle here to get calculate amount in cart
Comment: Hello and welcome. Have you tried to make some research on your own? We can't build functionality for scratch for you here.
Answer: For building a e-commerce website you should try the drupal commerce module or commerce_kickstart (If you are novice with drupal then commerce_kickstart is the option).
Drupal Commerce

Core Features
Create product types with custom attributes
  Dynamic product displays
  Order management, line item
  Payment method API, allowing many different payment gateways
  Tax calculation / VAT support
  Discount pricing rules
  Deep integration with systems like D7's Fields, Views,Rules and Entity API.

Commerce Kickstart

Commerce Kickstart is the quickest way to get up and running with
  Drupal Commerce. It includes the latest versions of Drupal core,
  Drupal Commerce, and the other modules it depends on. It also gives
  you a set of options to create a fully-featured demo store out of the
  box complete with an attractive theme, catalog and search
  configuration, and a custom back office interface.
  Who should use Commerce Kickstart? Anyone who wants to skip weeks of
  configuration to build a commerce site on the Drupal Commerce
  framework.
Comment: I only want to say that I would advise using Commerce over Ubercart (the other big Drupal eCommerce module).  Ubercart is old, messy, and the documentation is becoming dated.


What is the standard form of a linear programming (LP) problem?

Question: According to Bertsimas' text, the standard form of a LP problem is:

According to Vanderbei's text, the standard form of a LP problem is:

So, what is the standard form of a linear programming (LP) problem? Thanks.
Comment: Bertsimas' text refers to [*Introduction to Linear Optimization*](http://www.amazon.com/Introduction-Linear-Optimization-Scientific-Computation/dp/1886529191). Vanderbei's text refers to [*Linear Programming: Foundations and Extensions*](http://www.amazon.com/Linear-Programming-Foundations-Extensions-International/dp/1441944974).
Comment: Every author has his/her own convention. Some prefer the minimization formulation; some prefer the maximization form, and... you get the idea. Go with what you're comfortable with.
Answer: I have seen both the $\min$ and $\max$ forms of an LP frequently, it seems to be an author preference sort of thing. The only difference is a minus sign in the objective ($-c^Tx$ instead of $c^Tx$).
Regarding the constraints, I have more often seen the first form (your Bertsimas reference) referred to as standard or canonical. The two forms are equivalent in some sense.
Since $Ax=b$ can be written as the pair of inequality constraints $Ax \leq b$ and $(-A)x \leq (-b)$, it is clear that the first form can be expressed directly as a problem of the second form.
The inequality $Ax\leq b$ can be written as a combination of an equality $Ax+ \sigma = b$ and an inequality $\sigma \geq 0$. Hence by increasing the number of variables (ie, using the variables $x$ and $\sigma$), we can express the second form as a problem of the first form, ie, $\begin{bmatrix} A & I \end{bmatrix} \pmatrix{x \\ \sigma} = b$, $\pmatrix{x \\ \sigma} \geq 0$.
The problem $\min \{ c^T x | A x \leq b \}$ is sometimes referred to as an inequality form LP. Again, it is equivalent to the other two forms.
Comment: Thanks @copper.hat. Perhaps it is indeed a matter of preference. In Bertsimas' own words "we will often use the general form $ \mathbf{Ax} \geq b $ to develop the theory of linear programming. However, when it comes to algorithms, and especially the simplex and interior point methods, we will be focusing on the standard form $ \mathbf{Ax} = b, \mathbf{x} \geq 0 $, which is computationally more convenient."
Answer: Both are standard form. The Objective Function (first line) can be aimed to either minimize OR maximize, the constraints (everything after "subject to") can be many or few, and the constraints can be in any of the following forms: >=, =, or <=


Expected total number of flips for a game.

Question: Consider there's a game:

Player A flips a fair coin until a tail comes up.
Player B flips a fail coin until getting the same number of heads as A in a row.

Question: what is the expected number of flips in the game?
My thought: If A flips $a$ times and get the first tail, B needs to get $a-1$ consecutive heads, denote the number of times B flips as $b$, it is known that $E_a[B] = 2^a-2$.
To calculate the expected total flips,
$$E[a+b] = \sum_{i=1}^{\infty}\frac{1}{2^i}(i+2^i-2)$$
which is divergent.
Is that correct?
Comment: If person A flips k times the probability of finally getting tail is like geometric dist. : $\frac{1}{2^k}$ and so person B has to do $k-1$ heads in a row, which is $\frac{1}{2^{k-1}}$ and the probability together is $\frac{1}{2^k} \cdot \frac{1}{2^{k-1}}$ and expectancy is $\sum_{k=1}^{\infty} 2k \cdot \frac{1}{2^k}$ no? which is $E = 4$
Answer: Let $N$ denote the total number of flips in the game, $N_A$ the number of flips of player $A$ and $N_B$ the number of flips of $B$. Furthermore, denote with $H_A$ the number of heads flipped by $A$. We seek
$$\mathbb{E}[N]=\mathbb{E}[N_A+N_B]=\mathbb{E}[N_A]+\mathbb{E}[N_B].$$
Note that $N_A\sim\text{Geom}\,(1/2)$ so $\mathbb{E}[N_A]=1/(1/2)=2$. Also,
$$
\mathbb{E}[N_B]=\mathbb{E}[\mathbb{E}[N_B\vert H_A]]=\sum_{n=1}^\infty\mathbb{E}[N_B\vert H_A=n]\mathbb{P}(H_A=n)=\sum_{n=1}^\infty\mathbb{E}[N_B\vert H_A=n]\left(\frac12\right)^{n+1}.
$$
To compute $\mathbb{E}[N_B\vert H_A=n]$, consider the trivial case $n=2$. How many flips does $B$ need to make to obtain $2$ heads? The first head follows a geometric distribution and so does the second. In general, the sum of geometric R.V.s is a Negative Binomial with parameter $n$ and $p$, therefore the desired expectation is the mean of a NBD,
$$\mathbb{E}[N_B\vert H_A=n]=n/(1/2)=2n.$$
It follows
$$\mathbb{E}[N_B]=\sum_{n=1}^\infty2n\left(\frac12\right)^{n+1}=\sum_{n=1}^\infty n\left(\frac12\right)^n=\underbrace{\sum_{n=1}^\infty n\left(\frac12\right)^{(n-1) }\frac12}_{\text{mean of Geom(1/2)}}=2.$$
Thus,
$$\mathbb{E}[N]=\mathbb{E}[N_A]+\mathbb{E}[N_B]=2+2=4.$$

Edit:
I misread the problem, the above works for player $B$ flipping $H_A$ heads in total, not in a row. It suffices to make a small adjustment. Let us make a slight generalization. Denote with $X_i$ the total number of successes attained up to the first time there have been $i$ consecutive successes, and with $A_{k-1,k}$ the number of additional successes aftet there have been $k-1$ successes in a row until there have been $k$ in a row. It follows
$$X_k=X_{k-1}+A_{k-1,k}\implies \mathbb{E}[X_k]=\mathbb{E}[X_{k-1}]+\mathbb{E}[A_{k-1,k}].$$
Now, note that if we have accumulated $k-1$ successes and if the next one is a success (with probability $p$) then we are done, if not, we start all over again. So
$$\mathbb{E}[A_{k-1,k}] = 1\cdot p+(1-p)\mathbb{E}[X_{k}+1]$$
substituting and simplfying yields
$$\mathbb{E}[X_k]=\frac1p+\frac{\mathbb{E}[X_{k-1}]}p.$$
Using the fact that $\mathbb{E}[X_1] = 1/p$, we have that the expectation of $k$ successes is
$$\mathbb{E}[X_k]=\frac1p+\frac1{p^2}+\cdots+\frac1{p^k}.$$
Now, going back to our problem we have
$$\mathbb{E}[N_B\vert H_A=n]=\sum_{i=1}^n2^i=2^{n+1}-2.$$
So
$$\mathbb{E}[N_B]=\sum_{n=1}^\infty\left(2^{n+1}-2\right)\left(\frac12\right)^{n+1}=\infty.$$

Edit 2:
I wrote a really basic simulation of the exercise in python to test the result above. It indeed seems to diverge.
<code>import random

for i in range(1,7):
    sumNs = 0
    sims = 10**i

    for j in range(sims):
        N_A = 0
        N_B = 0
        H_A = 0
        N = 0
        #counts the heads in a row
        count_head = 0

        while True:
            # 0 = Tails, 1 = Heads
            coin_flip = int(2*random.uniform(0, 1))
            N_A += 1
            if coin_flip == 0:
                break
            else:
                H_A += 1

        if H_A != 0:
            while True:
                coin_flip = int(2*random.uniform(0, 1))
                N_B += 1
                if coin_flip == 1:
                    count_head += 1
                    if count_head == H_A:
                      break
                else:
                    count_head = 0

        else:
            continue

        N = N_A + N_B
        sumNs += N

    print(str(i)+". Simulations: "+str(sims)+". E[N]: "+str(sumNs/sims))
</code>


s3cmd, set low verbosity

Question: I currently use s3cmd to sync backups from our servers to amazon s3. I do this using a cron similar to the following:
firstname.lastname@example.com
01 03 * * * s3cmd sync /root/backup/backups/ s3://somebucket/

This is just a sample, the files to be synced are already in the backups directory. Currently when I use this, I quite often get warnings about the upload fails (connect reset by peer) and then the retries. After 1 or 2 retries the upload generally gets there.
What I'd like to know is can I change the verbosity of s3cmd to only log output when it actually errors, rather than warns so that I only get emailed when I need to look at something?
It appears you might be able to set this in the .s3cmd preference file, but I wanted to make sure.
Thanks
Answer: If you have a newer version of s3cmd, try the --quiet (or -q) option:
firstname.lastname@example.com
01 03 * * * s3cmd sync --quiet /root/backup/backups/ s3://somebucket/

If not, just redirect STDOUT to /dev/null like so:
email@example.com
01 03 * * * s3cmd sync /root/backup/backups/ s3://somebucket/ >/dev/null

Errors are sent to STDERR so they will still be emailed out.
UPDATE ABOUT S3CMD and STDERR:
As Valguss pointed out, it seems that s3cmd always logs debug, info, warning and error messages to STDERR so the above methods will not work.
However, the verbosity level can be controlled from the .s3cfg file (located in the home directory for the user associated with the cron job in this case):
[default]
verbosity = ERROR

A verbosity level of ERROR can not be configured via command line parameters at this time.
Comment: Thanks for that. I've had a look, and the quiet option is in the 1.5 alpha 3 release on github, the release version on their YUM repo is 1.0. I'll give the redirection a go and see what happens.
Comment: OK, just checked and redirection dosen't work either. It appears that the warnings are sent to stderr as well. I'll email the author and see if they can shed some light.
Comment: Still get all the same output after changing `verbosity = ERROR`. Not sure why this trick doesn't work.

s3cmd, set low verbosity


How to create a view that display on the same row a field and its translation

Question: Let say I have a content type with 2 fields that can be translated in a 2 languages site (EN-FR): the title and field_tobe_translated
I would like to list (in a view) all nodes of this content type with only one row by node and each row should have this format:
Title_FR -- Title_EN -- translatable_field_FR -- translatable_field_EN
The "--" before means a column separator in a table type view.
Added question:
Is it possible to filter this view to show only the row where "Title_FR != Title_EN" [I assusme that the process would be the same for the other translatable field]
Answer: I haven't found a way to show translations in the same row as the source, without additional modules that is. Although that would be nice to have.
These modules aren't currently covered by Drupal's security advisory policy so they might not be a wise choice:

Translation Views
Views entity translation shortcuts
Translate Side by Side

A compromise might be to show your information spread accross two rows instead of one:

Create Views showing Title and Field for the two languages
Sort by ID (this will list translations close to their sources so you'll end up with pairs of English and French nodes that are translations of the same content)
Add another Sort criteria by Language (this way you're sorting inside each pair, so you always get French first, English second, if that's how you prefer it)

So in the end you'd have:
+----+------------+-------------------------+
| ID | Title      | Field                   |
+----+------------+-------------------------+
| 1  | Title_FR_1 | translatable_field_FR_1 |
+----+------------+-------------------------+
| 1  | Title_EN_1 | translatable_field_EN_1 |
+----+------------+-------------------------+
| 2  | Title_FR_2 | translatable_field_FR_2 |
+----+------------+-------------------------+
| 2  | Title_EN_2 | translatable_field_EN_2 |
+----+------------+-------------------------+
| 3  | Title_FR_3 | translatable_field_FR_3 |
+----+------------+-------------------------+
| 3  | Title_EN_3 | translatable_field_EN_3 |
+----+------------+-------------------------+
Comment: Many thanks for this nice idea... If one of the module you are listing can answer this question, I will set it as answered.
Comment: Follow up: I didn't find a way to answer this question with "Translation Views" and "Views entity translation shorcuts", but maybe I missed something. I gaved a try to "Translate Side by Side" but the module is unusable (I filled a bug report)... wait and see...
Comment: I haven't yet figured it out, need to investigate further, or someone more knowledgeable comes along.
Answer: I knew there was a way, even if it's the old way (I expected it would be possible in D8 out of the box).
Use Views Field View module
You can do it with the help of Views Field View. It's basically embedding a View into another View to be displayed as a field.
You have to have the Child View created before you can add it to the Parent Views. Parent and Child can be two Displays on the same Views, they don't have to be in two different Views.
In your case your Child View will be filtered to show only fields related to one node (using regular and Contextual Filters), so you can end up with a nicely styled result where one node information is displayed in one table row.

Create a Views Display of type Embed to serve as your Child Display.
Filter it to list your content and also add the Filter
Content: Translation language and set it to French (Or English)
Add Title and the other field you want to see
Format Unformatted list and under Fields Settings set both fields as Inline, separator may be something like |
Add a Contextual Filter Content: ID and configure it to:
When the filter value is NOT available
Provide default value
Content ID from URL
(Optionally specify validation criteria)
Create a Page view (you probably have this already) of Table Format
Filter it to list your content and also add the Filter
Content: Translation language and set it to English (Or French, the opposite from the one which you set in Step 2)
Add a Field Content: ID and Exclude it from display. This info will be fed to the Embedded view to filter only translations for that node
Add the Title and the other field you need to show
Add the field Global: View and under View settings select the View name from the first dropdown
Apply
Save the View
Edit the Global: View again, this time you'll be able to choose the exact Views Display you created in step 1
In the Contextual filters enter {{ raw_fields.nid }} or whatever makes sense in your case, check under Replacement patterns

You should now see the list of nodes with English and French fields on the same row.
The Inline fields might not emulate the Table cell look exactly. You can make this display as table cells exactly with some more elaborate HTML overwrites to make them blend together.


How can I filter entity titles in an autocomplete form and use the title as context for a View page?

Question: I am trying to provide a form with a single autocomplete text field on the front page.  The user can search for a title of the product (commerce_product), and when they submit, they're redirected to a views page with the title as context.
These are baseball cards from multiple sellers, so there can be many cards and variations of a single card with the same name, e.g. multiple sellers sell a "Barry Bonds" card.
When the user enters the name of the card and submits, I need to redirect them to a views page to display all the cards for that particular title (card name).
The part I'm trying to figure out is how to use the selected title on the front page and send the user to a views page with that title so I can use it in a view. I assume that would be a Context, but I'm not having success finding how to do that.  To clarify the flow:

User hits front page and searches for a product title.
The user submits and is redirected to a views page.
On the views page, the user can browse all the cards under that title.
Comment: Isn't what you're after already what Views do? You enter a keyword into the autocomplete field of the Exposed Filter for the Title field, and you get a list of results, nodes that satisfy the criteria. What is it about that that doesn't suit you? BTW it seems your structure might be improved if you created a Taxonomy Vocabulary for all the Players and let sellers select from an existing list instead of relying on them to enter the name into the Title field. You can even use Autotitle or similar to automatically create Titles out of entered info, and use Taxonomy terms for contextual filtering.
Comment: You can use the `Input required` (Only display results after the user has selected a filter option.) it's under the `Exposed form style` setting. Or you can use the  `Exposed form in block` if your Views is a Page Display, so you only show the Filters block of that View somewhere on your site, and when the user uses it, they get redirected to the Views page.
Comment: Many websites have very long taxonomy lists and Drupal is able to handle them. There are lists/databases in various formats of various things, that can be imported into Drupal. Baseball db might not be free, but maybe you don't need all? You could let users create the Taxonomy entries too, you already allow them to fill in the Titles correctly, using a different structure in the back-end might help handling the site building, while keeping the same user experience.
Comment: I don't want the view results on the first page.  There's other supplemental content on the first page.  The View page is dedicated to search results.  Regarding Taxonomy, I don't think it's feasible to create a taxonomy entry for potentially every baseball player who's ever lived.
Comment: @prkos I don't doubt Drupal can handle it, but that's just not feasible.  I have a DB source (custom autocomplete) the user pulls from when they add a new product for sale.  I'm thinking I'll select back the player name to get the ID, then on the submit I'll redirect to the view page with the context in the URL.  I'm thinking that's the way to do it so far.  Also, there's no view on the front page.  The user would be directed to the view page after entering the player name.
Answer: Here's how I solved my problem:

Added an ID field (the ID from the source I'm pulling/validating player names) to my variation.  On creation of a variation, I store the ID in the field when the user selects the player name during product creation, e.g. "Barry Bonds" is ID 35456 in my source.
I'm using a regular autocomplete route in my form instead of an entity_autocomplete.  My autocomplete handler does an entity query on cards (product variations) that are active and match the player name.
After the player is selected from the autocomplete, on form validation, I re-select the player to get the ID.
On form submit I pass the ID with the URL to my views page as a contextual filter, where it expects it as a field value in the URL, e.g. "/player-card-search/35456".

Creating the new ID field in my product variation feels redundant, but it got me to the solution.


Função para criar hash no padrão SRI

Question: Estava a olhar para uma nova especificação W3C SRI (Subresource Integrity) o que a grosso modo quer dizer Integridade do Sub-recurso que promete trazer mais segurança a recursos hospedados em servidores de terceiros (ou no próprio) ja em uso por BootstrapCDN, CloudFlare, GitHub e jQuery embora ainda seja nova e não tenha uma ampla implementação pelos navegadores.
Basicamente a nova especificação adiciona a tag script dois novos atributos:

integrity: que contém a hash criptográfica do arquivo
crossorigin: por padrão "anonymous"

A documentação (simplista) descreve o uso de OpenSSL via linha de comando para criar a hash:
Instrução de linha de comando para gerar a hash
openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

Minha questão é: como usar a funções openssl do PHP para chegar ao mesmo resultado (gerar a hash de um arquivo)?
Referencias:

SRI Hash Generator: ferramenta online
W3C Subresource Integrity: especificação
caniuse.com: suporte
Mozila Docs: documentação
Mozila Hacks: artigo
Answer: Você tem o hash_file() no PHP, que a variação do hash() justamente para arquivos, que é similar ao morto md5_file().
$algoritmo = 'SHA512';
$arquivo = 'arquivo.js';

$hash = hash_file($algoritmo, $arquivo, true);

$integrity = strtolower($algoritmo) . '-' . base64_encode( $hash );

Dessa forma basta utilizar:

Função para criar hash no padrão SRI


Best practice MLR vs GLM(M)

Question: I am modelling timeseries of organism traits (7 different traits in total) using GLM(M)s in R. The data was collected at very irregular intervals and from 6 different locations. For every location 5-10 animals were sampled and some locations have been sampled multiple times whereas others just once or twice.
I am interested to see if Trait significantly changes with Year.
I decided to use Location as a random variable so that the model is of the form:
glmer(Trait~ Year + Var1 + (1|Location),
               family=gaussian(link = "log"),
               data = data)

The model diagnostics lock good and don't give any reasons for concerns to me.
I did just for the sake of it model the same traits using multiple linear regression, this time having Location as a fixed term. This required the log transformation of Traits
lm(log(Trait) ~ Year + Var1 + Location, data = data)

Also for these models the diagnostics look good.
Both models suggest the same trend in the data.
Now the problem that I am facing is decide what model I should use? In the literature it is commonly mentioned that the simplest possible statistical tool should be favored over more complicated ones which suggests to me I should favor the linear regression but one is also discouraged to transform data to fit the model.
Comment: Note that there is a difference between a model with a transformed response & with a link function for the mean (see: [Why is GLM different than an LM with transformed variable](https://stats.stackexchange.com/q/122103/7290)).  These can't both be right.
Comment: How many locations do you have?
Comment: 6 different locations
Comment: @gung-ReinstateMonica is quite right. I have updated my answer. You need to be consistent in what you are modelling.
Answer: 6 is considered to be at or very near the lower limit for fitting random intercepts. In your case I would suggest the linear model with fixed effects for location. If this is for publication / presentation then I would also mention that you have fitted a mixed model with random intercepts for location, and found that the inferences were very similar.
Also, note that, to be consisent, you should fit the models:
glm(Trait ~ Year + Var1 + Location, family = gaussian(link = "log"), data = data)

and
glmer(Trait ~ Year + Var1 + (1|Location),family = gaussian(link = "log"), data = data)

OR,
lm(log(Trait) ~ Year + Var1 + Location, data = data)

and
lmer(log(Trait) ~ Year + Var1 + (1|Location), data = data)

Comment: Thank you very much! This answer is great.
Comment: You're welcome. Happy to help !

Best practice MLR vs GLM(M)


Wrist problems when using the first fret

Question: One perennial problem I've had for as long as I can remember is that any time I play a song that uses the first fret a lot (e.g. the verses for Metallica's "Jump in the Fire" come to mind) I end up hurting my wrist real bad.
12 years of playing tells me that it's not something that's simply going to go away with time.  It seems the issue is mostly with having to stretch my index finger across the neck, and the pain is primarily in my wrist right at the base of the round part of the palm.
Does anyone have any advice on what I can adjust to alleviate this issue, aside from playing songs that are predominantly in F?
Answer: The question that immediately came to my mind is, how low do you have your guitar on your strap?
If you're doing anything resembling a gun-slinger, you might want to raise it, because it directly affects the angle of your left wrist.
It will feel weird at first, but you will adjust to it quickly. Give it a try for a day or two and see how your wrist feels.
Comment: Following @theTinMan's advice, will straighten your wrist, this will in turn straighten your metacarpal tunnel. This in turn will lead to healthier tendons in your finger muscles which are located (mostly) in your forearm, not your hand.
Comment: Since this will fix a physiological issue, do not expect immediate results. Stick with this fix for a while and probably and eventually the problem will clear up.
Answer: I'd say it depends almost entirely on your wrist position. If you're bending your wrist a lot, consider rotating your left arm down so your wrist isn't bending. I'm sure you've tried this, but...  No pain should be the norm.
Answer: The TinMan's suggestion is great, this answer is a complement or in addition to his. You probably use your thumb to squeeze or lock your hand down to the strings. Try getting some strength in pressing the strings down, by instead pulling the strings down from your biceps. This will also have the added benefit of straightening your wrist a little as well. This will also involve your right hand as you support the guitar there as well. More muscles that you use to alleviate the burden on your wrist. It is possible, thou not advisable, to completely eliminate the need for your thumb. You just want to reduce your thumbs role.


RAM not compatible

Question: I'm new here and new to servers in general, so I might just be overlooking something. I recently was given a few free Apple Xserves (3,1). I decided I would try to build a single better server from all of them so took some 2GB RAM sticks from one of the Xserves and added it on to a board with 8GB RAM sticks. When I tried to boot up the server, it wouldn't boot and the system activity lights were flashing, indicating a DIMM error. Could these RAM sticks be incompatible? They both came from an Xserve 3,1 and I know all of the RAM works. The server boots fine with just the 8GB sticks or the 2GB sticks, just not the two together. Both sticks are 1066 MHz DDR3 ECC. Thanks!
Comment: when I am new to something, I find it is good practice to read the documentation related to it.
Answer: The Xserve Setup Guide states that all the DIMMs must be identical. Therefore, you cannot mix different sizes of DIMMs in the same Xserve.
(Note that identical means that they must have the same specifications for size, speed, and timings. They don't necessarily have to be the same brand, but using RAM that Apple didn't sell you may invalidate the support contract you don't have anyway.)
Also note that you need to install the DIMMs in specific slots depending on how many DIMMs you have and whether the server has one or two CPUs installed. The Xserve Setup Guide has an illustrated display showing which slots to use.

RAM not compatible


Stored procedure to update parent in MySQL

Question: I have 2 tables for representing sensors and their values:
Unit:
  id
  name
  last_data

Data:
  id
  timestamp
  temperature
  unit

So basically I have multiple Data rows for each Unit.
I want to add a SP so every time I insert a Data row, it will automatically update last_data column in the matching parent (to point to the newly create id.
pseudo code:

new_id = INSERT INTO Data (temperature, unit) VALUES (25, 1);

UPDATE Unit SET last_data = new_id WHERE id=1

Not sure how to write such procedure...
Answer: You can use LAST_INSERT_ID() to get the ID of the last record that you've created within your session.
So you pseudo code would become something like:
INSERT INTO Data (temperature, unit) VALUES (25, 1);
SET @new_id = LAST_INSERT_ID();
UPDATE Unit SET last_data = @new_id WHERE id=1

Or even shorter:
INSERT INTO Data (temperature, unit) VALUES (25, 1);
UPDATE Unit SET last_data = LAST_INSERT_ID() WHERE id=1

https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
Comment: @GiladNovik: ask a new question then. Your original question asked for something different. If you change the question, all answers become invalid.
Answer: This can help you to solve you problem:
INSERT INTO Data (temperature, unit) VALUES (25, 1);

this our trigger:
CREATE TRIGGER update_last_data
    AFTER INSERT ON 'Data' for each row
begin
    SET @last_id_in_data = LAST_INSERT_ID();
    UPDATE Unit SET last_data = @last_id_in_data WHERE id=1;
END;


MIDI Recording: Release of Sustain Pedal kills the key sound

Question: TLDR: When recording my piano over MIDI, any time I release the sustain pedal, the played keys get killed off immediately, which doesn't happen on my Clavinova. What's the cause?
I recently built a setup to finally record all my songs which I did on my Clavinova CVP-105 on Floppy Disk throughout the last 15 years.
I'm afraid the piano might die one day or the floppy disks might not be readable anymore so I want to save them somehoe for the future.
My setup:
Yamaha Clavinova CVP-105
Alesis IO2
Surface Book 2
Reaper
Piano One VST
My problem is:
When I record and listen to the recorded songs on Reaper I noticed something I never heard before. Everything sounds more choppy and the reason is the sustain pedal.
When I'm holding down keys and relaese the sustain the pedal, the Clavinova still holds the key, you can still hear it fading out.
But on the MIDI it someohow kills the currently played keys making it sound choppy. I can see in the MIDI sheet that the key is being kept down, so release point is the same as on my clavinova but if I release the pedal in the middle, the key is also just played until that point.
I am using the sustain quite a lot since the Clavinova is not mudding everything together even if I hold the sustain for longer, meaning it has quite a short sustain per key which sounds super nice on it, but I can't record like this on MIDI since the VST I'm using (Piano One) will hold the keys much longer and everything builds up to a blur.
So what is causing this? Is it that particular Piano VST plugin I'm using?
Will it be better on another one?
I'm thinking about buying the Walker 1955 Concert D plugin but if the problem is the same there I might not spend 100 bucks on it.
Thanks!
Answer: Bit too much for a comment, but not really an answer as yet…
Some things to check - the Clavinova very likely is capable of using & sending the entire scale of CC64 [pedal].
The sequencer [or the VSTi] might only be using switch values of 0 & 127, or the worst, it toggles at values 63/64, making your pedal data well out from where you thought you played it.
Check also that the sequencer is not sending any 'all notes off' information & if it has a switchable pref, try with & without Running Status & see if is behaves differently.
[I can't help on specifics of Reaper, never used it.]
You should also test the files played back on the Clavinova as well as a couple of VSTis. There's also a chance the polyphony is lower on the VSTi, causing note-stealing.
Alternatively, get a floppy drive & import the files directly.
Worst case scenario, post one of the midi files [with a clear indication of one problem timestamp] & someone could have a look at the data...
Comment: I've looked at the data & though it sounds odd, it is in fact playing "what's written". See pic - https://i.stack.imgur.com/htKvh.png - the 2 highlighted notes are the truncated ones. You can see that the Pedal up is just before that. Is this the actual original file from the Clavinova, or a re-record? I suspect a re-record via something that's not correctly capturing the subtleties of the original pedal data & badly guessing at 0 & 127 values, instead of allowing full pedal travel smoothly from 0 - 127. I'd be interested to see the original file, if you can get it off the floppy disk.
Comment: Here I have an example MIDI file with a MIDI log. it happens 2 times in the first 10 seconds of the track (afterwards it does not happen anymore). Suddenly all key stop. https://we.tl/t-5zYCmrV6Pp
I'm just a newbie in terms of MIDI so its hard for me to decipher this.
Comment: Thanks for looking into it. Yeah its a re-record. I asked the Yamaha support and they told me the Pedal on my Clavinova is just a toggle, so I dont think it really sends a velocity so to say but only On/Off signals. But I can't believe this is something a piano VST or Midi sequences could have problems with.....I really have to try out other VSTs to see if they can somehow interpret this better....thats my only chance...
Comment: It's not the VST playback at issue. It's playing back what the file is telling it to. If the CVP doesn't have continuous pedalling, then something went wrong in the data transmission/reception as it was being re-recorded. The only way to know that for certain is to be able to compare it to the original file on floppy.
Answer: You could isolate whether the cause is the VSTi by playing the MIDI through one of the different free VSTi's included in Reaper.
If you're seeing the notes stay active on the MIDI data then you can rule out the keyboard/MIDI-in, and I don't see any Reaper MIDI settings that relate to this behavior so I'd lean towards it being some setting or limitation on the VSTi.
Comment: I checked it also happens with other VSTs (the Reapoer Synth) also abruptly stops playing.
Here is an example file (only the first 10 seconds are important). There it stops 2 times.
https://we.tl/t-5zYCmrV6Pp


cakephp find() question

Question: I want to convert following mysql statement into cakephp query syntax.Please help me. Here is my query.SELECT * FROM post WHERE (user_id == $id OR awarded_to = $id ) AND id = $id
Here is my cakephp query. is it wrong.
 $this->Post->find('all',
            array('conditions' => array('OR' =>
                                        array('Post.user_id' => $id),
                                        array('Post.awarded_to' => $id)
                                        ),
                                        'AND' =>
                                        array('Post.id' => $id)
                ))

Answer: This one's on the house, but next time read the docs.
   $this->Post->find('all', array(
            'conditions' => array(
                'OR' =>  array(
                    array('Post.user_id' => $id),
                    array('Post.awarded_to' => $id)
                ),
                'Post.id' => $id
            )
        ));

The 2 OR arrays need to be inside an array themself, and there's no need for AND.
Answer: Just add Post.id = $id below the OR condition without you give "and" it's automatic read as and condition...
$this->Post->find('all', array(
         'conditions' => array(
             'OR' => array('Post.user_id' => $id),
              array('Post.awarded_to' => $id)
         ),
         'Post.id' => $id
    ));

Answer: You are very close with your query, just you need little modification like to remove 'AND' in conditions array after 'OR' as:
$this->Post->find('all', array(
        'conditions' => array(
            'OR' =>  array(
                array('Post.user_id' => $id),
                array('Post.awarded_to' => $id)
            ),
            'Post.id' => $id
        )
    ));

Or
$this->Post->find('all', array(
        'conditions' => array(
            'Post.id' => $id
        )
    ));

The second option will be the best for you if you are passing tables primary key 'id' in AND conditions.

cakephp find() question


Is It Possible To Spring Autowire the same Instance of a protoype scoped class in two places

Question: ** changed the example to better express the situation
i am using spring 2.5 and have the following situation
@Component
@Scope("prototype")
Class Foo
{
}

class A
{
  @Autowired
  Foo fooA;
}

class B
{
  @Autowired
  Foo fooB;
}

class C
{
  @Autowired
  Foo fooC;
}

i am trying to understand if there is some way to use @Autowired and bind the same instance of FOO onto
fooA and fooB while binding a different instance to fooC
i understand that if the scope of FOO will be singleton it will work
but i am wandering if there is a way to achieve the same goal while using a protoype scope.
also please explain is this the correct usage of the autowiring concept ? am i trying to abuse the spring framework purpose
Answer: Since neither singleton nor prototype scopes seem to fit you (you don't want a single object, but you don't want a new instance each time), you need another scope.
In a web-application context there is a ready solution - use request scope - thus in every request/response cycle you will have only one instance of your bean, no matter where and how many times you inject it.
In a non-web application context you can define your own implementation of org.springframework.beans.factory.config.Scope
Update: after you clarified, this seems like a very strange case. What comes to my mind is the following:

define two FactoryBeans (actually - subclasses of AbstractFactoryBean)- one returning new object every time, and one returning the same object (both of them should be in singleton scope)
inject the Foos with @Resource(name="prototypeFactoryBean") and @Resource(name="singletonFactoryBean") (instead of @Autowired)
the singletonFactoryBean can be designed to just return a singleton (injected in the factory bean class)
the prototypeFactoryBean can create a new instance, cast the BeanFactory (available through getBeanFactory()) to AutowireCapableBeanFactory and call .autowire(newlyCreatedBean), and then return it. (alternatively you can inject an ApplicationContext and get its AutowireCapableBeanFactory)

But this is overly complex and you will need extended spring knowledge even after my explanation :)
Furthermore I think you should reconsider your design instead of making the above 'quirks'
Update 2: After your comment, the naming concept is transferred to annotations - as I indicated above you can use @Resource(name="someBean")
Comment: i am using a non-web configuration, so the suggested solution does not apply, also my explanation above was oversimplified i will revise it
Comment: thanks . i agree with all you said above. i know it seems like a weird scenario but if you think about it there are many occasions in a complex project where several instances of a specific class are shared among other classes. if you think about the spring XML configuration then it is handles very simply by "naming" , you just define two beans with different names represented by the same "code" i was merely trying to see if this capability was transferred to annotations, it seems a little inconsistent
Answer: The whole point of prototype scope is that you get a different instance each time.
Also, autowiring a prototype-scoped bean is questionable, design-wise (in fact, I'd be mildly surprised if it was even permitted). The usual idea is to autowire together beans of the same scope (there are ways around this, but not relevant here).
Everything about your design suggests that Foo should not be a prototype - why have you made it so?
Comment: the example above is a simplified expression of my situation
i am using a bean in the form of prototype because it is needed in my current configuration, there are many places where the bean is injected and a new instance is needed for each of them.
but there is a specific place where i would like two objects to share the same instance of the a third object and i wanted to see if it is supproted by spring
Comment: Perhaps you could configure multiple `Foo` singleton beans, and wire them up individually, using `@Autowired @Qualifier`
Answer: Autowiring prototype scoped objects is perfectly possible, but a new instance will be created each time. So to answer your question: no, you can't do that.
Your usage of component scanning and autowiring seems ok for the other part.


How do I expose a contextual filter?

Question: I have created a view that shows few entities. To be able to see only a particular entity, I created a contextual filter.
How can I expose the contextual filter I added?
Comment: Welcome to Drupal Answers! There isn't anything you need to do: The Views module applies both the contextual filter and the other filters to filter the entities to show.
Comment: I see, but how can I make contextual filter exposed for the user?
Comment: That is not the question you are asking, since _sum up_ doesn't mean _exposing the contextual filter to the users_.
Comment: Sorry, I will create a new question
Comment: There is no need to create a new question. It's enough to make this question clearer, which is what I did.
Comment: Just add it as a normal Filter Criteria.
Answer: Contextual filter is an an argument to the view, for example through the path or block/plugin context.
It is not visible to the user, it's visible to Drupal.
If you want something to be visible to the user, you need to instead add a filter and then tick the checkbox to expose it, creating a so called "exposed filter". That should then show up in a filter form.

How do I expose a contextual filter?


Contour integral of $f(z)=z$ from $z_1 = 5i$ to $z_2 = 2-2i$

Question: I have to make two different contour integrals of $f(z)=z$ from $z_1 = 5i$ to $z_2 = 2-2i$. I did the first contour to be $\gamma_1 (t) = 5i + t(2-2i)$ with $0\le t \leq 1$. But my question is how can I make a second contour different from the first one I have? Is it valid to do $\gamma_2 = (2-2i) + t(5i)$ with $0\le t \leq 1$? I was trying to make a contour with a half circle but I don't really know how to make it with parameters. I get that we will have $e^{it}$ with $0 \leq t \leq \pi$ but I don't know how to include the details of $z_1$ and $z_2$. Or is it easier to make another contour with just some random point in-between $z_1$ and $z_2$?
Thanks for the help.
Comment: You seem to have a mistake. $\gamma_1(t)$ at $t = 1$ should be $z_2$. So it should really be $z_1 + (z_2-z_1)t, 0 \leq t \leq 1$. Check the same for $\gamma_2$.
Comment: @MathLover yes, I forgot about the subtraction. It should be $\gamma_1 = 5i + t(2-7i)$. And $\gamma_2 = (2-2i) + t(-2+7i)$, are they different contours at all? And is $5i + t^2 (2-7i)$ a different contour?
Comment: No $\gamma_2$ is not different as all points are same as $\gamma_1$. But yes taking $t^2$ will keep the endpoints same but change the contour as $t \ne t^2$ for $t \ne 0, 1$.
Answer: You can take, say, $\gamma(t)=5i+t^2(2-2i)$ ($t\in[0,1]$).


Show that $x^3-\sqrt[ ]{3}$ is irreducible in $\mathbb Q(\sqrt[4]{3})$

Question: Show that $x^3-\sqrt[ ]{3}$ is irreducible in $\mathbb Q(\sqrt[4]{3})$
I suppose it is reducible and write:
$x^3-\sqrt[ ]{3}=(x-a)(x^2+bx+c)$
Then I solve the system of equations and get $a=\sqrt[6]{3}$
Now I should prove that $\sqrt[6]{3}\notin \mathbb Q(\sqrt[4]{3})$. But how to do that?
Thanks
Answer: $x^3-\sqrt{3}$ is reducible over $\mathbb Q(\sqrt[4]{3})$ iff it has a root in $\mathbb Q(\sqrt[4]{3})$.
If $\theta \in \mathbb C$ is a root of $x^3-\sqrt{3}$, then $\theta^6=3$ and so $\theta$ is a root of $x^6-3$, which is irreducible over $\mathbb Q$ by Eisenstein's criterion. Therefore, $\theta$ has degree $6$ over $\mathbb Q$ and so cannot be an element of $\mathbb Q(\sqrt[4]{3})$ since this extension has degree $4$.
Comment: Thanks, good point. I still would want to know how to prove that $\sqrt[6]{3}\notin \mathbb Q(\sqrt[4]{3})$....
Comment: The argument above is a proof that $\sqrt[6]{3}\notin \mathbb Q(\sqrt[4]{3})$.


What is the derivative of $f(x) = (x − y)^2 g(x)$

Question: I'm studying about Newtons Method and my notes say that if

$f(x) = (x − y)^2 g(x)$
  then $$f'(x) = 2(x-y)g(x) + (x − y)^2 g'(x)$$

Is this true? I thought it would be $$f'(x) = 2(x − y) g(x)$$
because $g(x)$ is just part of the multiplication.
Comment: Product rule of differentiation
Comment: Have a look at https://math.stackexchange.com/help/notation to format your mathematical notation
Answer: If $$f(x)=(x-y)^2g(x)$$then $$f'(x)=2(x-y)g(x)+(x-y)^2g'(x)$$

This happens because derivative of the product of two functions is the derivative of the first one multiplied by the second one plus the first one multiplied by the derivative of the second one.
i.e., $$(f\cdot g)'=f'\cdot g + f\cdot g'$$
and in your case $~y~$ is a constant.