Q:

Как динамично определять class_name для связи has_many, используя одинаковые таблицы разных engines

Здравствуйте, подскажите как определить связь, в зависимости от атрибута модели?
У модели User есть атрибут pay_currency, который может быть 'real' или 'bitcoin'. Есть 2 engines(Tbitcoin, Tstripe) у каждого из которых есть одинаковая таблица payment.
Необходимо найти способ, как создавая payment от юзера, направлять в нужный engine автоматически.
# Пример создания payments
User.create(pay_currency: 'real').payments.create # => Tstripe::Payments

Примерный код, для задумки
class User < ActiveRecord::Base

  has_many :payments, ~> { where "pay_currency = 'real'" } , class_name: Tstripe::Payment, foreign_key: :uid
  has_many :payments, ~> { where "pay_currency = 'bitcoin'" } ,class_name: Tbitcoin::Payment, foreign_key: :uid
end

В какое направление думать для реализации такой динамики?

A:

Во-первых, сделайте этим ассоциациям разные имена, а то они наложатся друг на друга и будет знатный ба-бах:
has_many :stripe_payments, class_name: Tstripe::Payment,
                           foreign_key: :uid
has_many :bitcoin_payments, class_name: Tbitcoin::Payment,
                            foreign_key: :uid

А потом просто сделайте выбор одной из двух ассоциаций. Есть целая куча способов.

Можно сделать в User метод, принимающий способ оплаты и возвращающий одну из двух ассоциаций (надо ловить случаи, когда получен несуществующий способ).
Можно сделать "создавалку платежей", одним из параметров которой является способ оплаты, и она внутри будет выбирать ассоциацию.
Можно просто разместить их в разных контроллерах и ссылаться не на "общие" payments, а только на конкретные.
Выбирайте любой.


Q:

Pandas pivot table using custom conditions on the dataframe

I want to make a pivot table based on custom conditions in the dataframe:
The dataframe looks like this:
>>> df = pd.DataFrame({"Area": ["A", "A", "B", "A", "C", "A", "D", "A"],
                       "City" : ["X", "Y", "Z", "P", "Q", "R", "S", "X"],
                       "Condition" : ["Good", "Bad", "Good", "Good", "Good", "Bad", "Good", "Good"],
                       "Population" : [100,150,50,200,170,390,80,100]
                       "Pincode" : ["X1", "Y1", "Z1", "P1", "Q1", "R1", "S1", "X2"] })
>>> df
  Area City Condition   Population Pincode
 0    A    X      Good   100       X1
 1    A    Y       Bad   150       Y1
 2    B    Z      Good   50        Z1
 3    A    P      Good   200       P1
 4    C    Q      Good   170       Q1
 5    A    R       Bad   390       R1
 6    D    S      Good   80        S1
 7    A    X      Good   100       X2

Now I want to pivot the dataframe df in a manner such that I can see the unique count of cities against each area along with the corresponding count of "Good" cities and also the population of the area.
I expect an output like this:
Area  city_count  good_city_count   Population
A        4        2                 940
B        1        1                 50
C        1        1                 170
D        1        1                 80
All      7        5                 1240

I can give a dictionary to the aggfunc parameter but this doesn't give me the city count split between the good cities.
>>> city_count = df.pivot_table(index=["Area"],
                                values=["City", "Population"],
                                aggfunc={"City": lambda x: len(x.unique()),
                                         "Population": "sum"},
                                margins=True)

    Area    City    Population
0   A       4       940
1   B       1       50
2   C       1       170
3   D       1       80
4   All     7       1240

I can merge two different pivot tables - one with the count of cities and the other with the population but this is not scalable for a large dataset with a big aggfunc dictionary.

A:

Another method without using pivot_table. Use np.where with groupby+agg:
df['Condition'] = np.where(df['Condition']=='Good', df['City'], np.nan)
df = df.groupby('Area').agg({'City':'nunique', 'Condition':'nunique', 'Population':'sum'})\
                       .rename(columns={'City':'city_count', 'Condition':'good_city_count'})
df.loc['All',:] = df.sum()
df = df.astype(int).reset_index()

print(df)
  Area  city_count  good_city_count  Population
0    A           4                2         940
1    B           1                1          50
2    C           1                1         170
3    D           1                1          80
4  All           7                5        1240


Q:

Can Cesium map run on Apache HTTP server instead of node.js environment?

I have an Apache HTTP server that handles all my requests for a Ruby on Rails project.  We are thinking of adding a Cesium map component.  I am wondering if I can run Cesium on the Apache HTTP server instead of setting up a node.js environment?

A:

Yes, Cesium is completely client-side and can be served by any HTML server.


Q:

Writing a c-string directly into a std::string

I want to get a log message from a C library. The library provides two functions :
int get_log_length(); // Returns the length of the string, including the terminating null character
void get_log(char *buffer); // Writes the log into buffer

I want to write that log into a std::string and return it. The normal way (I think) would be :
std::string get_log() {
    int length = get_log_length();
    char *buffer = new char[length];
    get_log(buffer);
    std::string str(buffer, length - 1);
    delete[] buffer;
    return str;
}

But I would like to skip using a buffer, so I thought of doing this :
std::string get_log() {
    std::string str;
    str.reserve(get_log_length());
    get_log(str.data()); // Bad: undefined behaviour
    return str;
}

But the size() of the std::string would remain unchanged, and would result in undefined behaviour (cf. cppreference).
Is there a way to only write the log once ?

A:

You'll want to resize the string instead of reserve:
std::string get_log() {
   std::string str;
   str.resize(get_log_length());
   get_log(str.data());
   return str;
}

This will update the string's underlying buffer to the appropriate size AND fill the string out with '\0' characters. Afterwards, those characters are overwritten by get_log
One thing to be wary of, though, is that get_log is likely going to try to write a \0 terminator to the string, which is not what you want in a std::string, so you may need to lop the last character off.
OR, the other way around; get_log_length() might return the size of the log message minus the terminating character (like strlen would), but get_log might try to write a terminating '\0' anyway, meaning that you'd need to size you string as get_log_length() + 1, and then afterwards str.pop_back to remove the terminator. Just double check this behavior.


Q:

How to init base class staic inline data member in derived class?

Say I am having a class like
#include<iostream>
#include<string>

template<typename CharT>
class base
{
   //.....
public:
   using string_type = std::basic_string<CharT>;
   static inline string_type var;
   //.....
};

class derived : public base<char>
{
private:
   using base<char>::var;
public:
   static base<char>::string_type get()
   {
      return var;
   }
};

//template<>
//base<char>::string_type base<char>::var = "Value";

int main()
{
   std::cout << derived::get();
}

base class accept a char type and creates a string type for that class, but I want to use that strng_type string in the class, so I created a static string_type variable that has to set by the user of the class.
For char the value is "Value" and For wchar_t value is L"Value". so I want to hide the var from a user by inheriting the class in specified type(char) now how to init that var.
I  have tried by removing the inline and uncomment the template it works but there is a way to init inline static base class variable.

How to init base class inline static data member?
It is a good idea doing this?

A:

How to init base class inline static data member?

Remove the inline and you should be able to initialize the var
template<typename CharT>
class base
{
public:
   using string_type = std::basic_string<CharT>;
   static string_type var;
   // ^^^^^^^^^^^^^^^^^^^
};

template<>
base<char>::string_type base<char>::var = "Value";

template<>
base<wchar_t>::string_type base<wchar_t>::var = L"Value";

It is a good idea doing like this?

Not sure about the design. Because what you mentioned here

"I want to hide the var from a user by inheriting the class in
specified type(char) [...]"

It looks like, it is still accessible via
std::cout << base<char>::var;


Q:

AppEngine/Java Cron DeadlineExceededException

I have cron setup in appengine project:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
    <cron>
        <url>/cron/someurl</url>
        <description>cron</description>
        <schedule>every monday 8:00</schedule>
        <timezone>Asia/Singapore</timezone>
    </cron>
</cronentries>

I am getting the error:
com.google.apphosting.api.DeadlineExceededException: This request (40811df3b6350a70) started at 2012/11/26 00:00:00.404 UTC and was still executing at 2012/11/26 00:09:59.917 UTC.

It's a 1-minute limit to run the task? I though cron doesn't have that limit. How to avoid the error in cron entry?
Thanks.

A:

An HTTP request invoked by cron can run for up to 10 minutes, as per the documentation. If you notice the exception log closely in the HH:MM:SS value, you will find that a total of 10 minutes have passed since the job was started.
You might want to look at your code to see why it is taking that long. In case you have requirements that make your tasks run longer than 10 minutes, I suggest that you look at trapping the exception and then inserting another request to run a job with some request parameter that tells the job to start from where it left off last time.
Alternately, you could also look at Backends.


Q:

Case Statement Not Working - VBA

In my project I have a list of clients that have unique commission calculations (ex. Client_1 has a 0.1% commission rate, whereas Client_2 has a 0.25% commission rate).
In my VBA code I made special cases, that vary by the client_id. The problem I'm getting with this code is that even though I put in a special ID, it jumps over the case (ex. if klienta_nr = 100, it skips over the Case klienta_nr = 100 and returns the Case Else). How can I fix this issue?
Private Sub CommandButton1_Click()

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double
Dim vk As String

Set kSheet = ThisWorkbook.Sheets("komisijas")

klienta_nr = Range("B2").Value
ISIN = Range("E2").Value
Cena = Range("H2").Value
Skaits = Range("I2").Value
vk = Range("B2").Value

Select Case klienta_nr

Case klienta_nr = 100

            If klienta_nr = 100 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            If klienta_nr = 100 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

            'Case where klient is special, but ISIN doesn't apply
            If klienta_nr = 100 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
                Komisija = (Cena * Skaits) * 0.003
                If Komisija >= 40 Then
                    Range("K2").Value = 40
                    End If
            End If

 Case klienta_nr = 105

            If klienta_nr = 105 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                Komisija = (Cena * Skaits) * 0.01
                Range("K2").Value = Komisija
                End If
            'Set 30 EUR Min
            If klienta_nr = 105 And Komisija <= 30 Then
                Range("K2").Value = 30
                End If

    'End If

 Case klienta_nr = 110

            If klienta_nr = 110 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 110 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 110 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

Case klienta_nr = 115

            If klienta_nr = 115 And (Left(ISIN, 2) = "NO" Or Left(ISIN, 2) = "SE" Or Left(ISIN, 2) = "DK" Or Left(ISIN, 2) = "FI" Or Left(ISIN, 2) = "IS" Or Left(ISIN, 2) = "LT" Or Left(ISIN, 2) = "EE" Or Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE" Or Left(ISIN, 2) = "AT" Or Left(ISIN, 2) = "BE" Or Left(ISIN, 2) = "ES" Or Left(ISIN, 2) = "PT") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.002
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "UK") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If

            If klienta_nr = 115 And (Left(ISIN, 2) = "CH") Then
                Komisija = (Cena * Skaits) * 0.002
                Range("K2").Value = Komisija
                End If
            'Set 20 [valūte] MIN
            If klienta_nr = 115 And Komisija <= 20 Then
                Range("K2").Value = 20
                End If

 Case klienta_nr = 120

            If klienta_nr = 120 And (Left(ISIN, 2) = "US") Then
                Komisija = (Cena * Skaits) * 0.0027
                Range("K2").Value = Komisija
                End If
            'Set 40 USD MIN
            If klienta_nr = 120 And Komisija <= 40 Then
                Range("K2").Value = 40
                End If

'Non-special klient cases
Case Else
    If Not Application.Match(klienta_nr, kSheet.Range("A2:A100")) Then

         If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
            Komisija = (Cena * Skaits) * 0.003
            Range("K2").Value = Komisija
            End If

        If Right(vk, 1) = 7 Then
            Komisija = (Cena * Skaits) * 0.01
            Range("K2").Value = Komisija
            End If
        'Komisija MAX is 40, so anything >=40 equals 40
        If Komisija >= 40 Then
            Range("K2").Value = 40
            End If
    End If
   End Select
  End Sub

A:

Select Case only needs criteria in
Select Case klienta_nr

And not in the Case part as below:
Change
Case klienta_nr = 105

to
Case 105


Q:

How can I show time passing with no way to measure time?

In the writing, I was doing recently, a character is locked up in a wagon and dragged across the country by rich slavers. How could I show the reader that time is passing when the character wakes up only occasionally, seeing very little of the outside world, and is drugged to unconsciousness whenever they are seen awake.
The character is in a caravan with many slavers and three other prisoners - two girls unknown to him, and a childhood friend he was captured with.

A:

What sort of time period are we looking at?  Hours?  Days?  Weeks?  Months?
Over a period of hours, it's going to be things like the angle of shadows (how high in the sky the sun is), the temperature, et cetera.
At days, it comes down to water breaks:  a dead slave is worth no money, so they need to be given something to drink occasionally.  Are the drugged slaves roused from their stupor just enough to manage this without drowning?
Once you reach weeks, you start to notice things like beards growing, or weight loss from not being fed properly.  Add food to the water breaks - probably a gruel of some sort, not particularly nice or nutritious, but still an indication that time has passed.
Consider also the Slavers themselves - the guards in the caravan will rotate through a shift schedule, they will (presumably) change clothes every so often.  And, finally, geography - different sounds and smells may indicate to the character that they must be at least such and such a distance from where they started.  Brine for sea ports, certain types of flowers or animals, the quality of the road or track that they are travelling on, the accents of people talking outside the caravan.

A:

Changes of light, of temperature, of weather, of season. Unremembered wear in clothing, the healing of wounds, loss of physical condition. Hair longer than ever before. Sudden brutal grooming from the captors and subsequent regrowth. Being let out to push a wagon out of mud. Sickness in the camp. Raiders, fended off. Capture by the raiders, and subsequent recapture by the slavers. Events.
It's a wagon, not Schrodinger's Catbox.

A:

I think George R. R. Martin does this quite well in his various novels. A good few characters in A Song of Ice and Fire are locked up at some point, and GRRM always dedicated a good couple of pages at least to hammering home how long they've been in captivity.
These chapters often deal with the mental toll of being confined to a place with no brain stimulation, just as much as the physical toll of wasting away. At the start of such a chapter, the character attempts to keep track of days by counting how often they're fed. Inevitably they lose count as the days start to blend together. They try to keep their mind occupied by playing games with themselves or by trying to recount old stories, but that inevitably stops after a while, and they find themselves sleeping most of the time. At some point, their dreams and waking become indistinguishable and they feel like they've been in captivity for decades even if the actual time spent is only a couple of months.
Your character's captivity will take a toll on him, both physically and mentally.


Q:

Sending password link to email when user forget password

I have the problem, how to send a password link to user email when the user clicks the forget password link....
Here is ForgetPasswordViewController.php... i developed this for simply showing a alert...
But when coming to real time.. i don't know how to send the password link.. to user email...
    <?php

      header("Cache-Control: private, must-revalidate, max-age=0");
      header("Pragma: no-cache");
      header("Expires: Fri, 4 Jun 2010 12:00:00 GMT");

//If you are not submitting the form HTML will be directly shown
         if (!isset($_POST['submit']))
          {
     ?>

       <form name='f1' method="POST" action=""  onSubmit="return ValidateEmail();">

       Email:
        <input  class="input" type="text" name="Email"   placeholder="Enter mailID" required>

        <input  style="height:50px; width:120px; background:url(Images/submit_butto.gif) no-repeat right top; border: none;" type="submit"  name="submit" value="">
       <?PHP
       }
      else
      {
         $Email=$_POST['Email'];
        if(!empty($Email))
        {
         $model = new UsersModel();
         $rowsCount = $model->checkUserEmail($Email);
          echo $rowsCount;
         if ($rowsCount!=0)
         {
//If you are submitting the form insert the details into database
        echo '';
     }
     else
      {
    echo'';
        }

        }
        }
      ?>

Any suggestions are acceptable....

A:

Use this code if you want to send an email:
$to      = 'recepient@somemail.com';
$subject = 'Subject here';
$message = "Content";
$message .= "more Content";
$message .= "even more Content or a variable".$variable;
$headers = 'From: sender@yourdomain.com' . "\r\n" .
'Reply-To: sender@yourdomain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);

Be aware that there are security issues like header injection if you don't validate the user input. A good email validation is this:
$to = $_POST["email"];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { /*mail is ok*/ }
else {/*mail is NOT ok*/}


Q:

derivative of x^x^x... to infinity?

I am a 12th grade student, and I am afraid that in realistic terms this question might not even make sense because of the infinities that have to be dealt with. However, in my attempt to calculate it's derivative, I did the following:
$$y=x^{x^{x^{.^{.^.}}}}$$
$$\ln(y)=\ln(x)x^{x^{x^{.^{.^.}}}}$$
$$\ln(y)=y\ln(x)$$
after taking derivative with respect to x on both sides, I obtained the following:
$$\frac{\mathrm dy}{\mathrm dx}=\frac{y^2}{x(1-\ln(y))}$$
I am fairly certain that the calculations up to this point are valid. However, to further continue, I analyzed the nature of y in different domains and obtained the values, by observation(that is, by observing how $x$, $x^x$, $x^{x^x}$, $x^{x^{x^x}}$, and so on would behave to draw a conclusion):

for $x<1,$ $y$ becomes 0
for $x=1,$ $y$ becomes 1
for $x>1,$ $y$ becomes infinite

These 3 points is where the first problem lies. Are these true? If so, how do we reach to the conclusion?
Secondly, considering this to be true,
I get the derivative at:

$x<1$ to be 0.
$x=1$ to be 1.
for $x>1$, I took $x=2.$ then the derivative $\frac{\mathrm dy}{\mathrm dx} = y^2/[2(1-ln(y))]$ (replacing $x$ by $2$). Now, I applied L hospital's rule to get the value of the expression to be negative infinity.

This is the second problem. I have used L Hospital's rule, but limits were not concerned. Is this method valid? If not, how would we calculate it?

A:

By following this link you will see that you function is well-defined over the interval $I=\left[e^{-e},e^{\frac{1}{e}}\right]$ and the values in the endpoints are just $\frac{1}{e}$ and $e$. Over such interval, the functional equation:
$$ f(x) = x^{f(x)} \tag{1}$$
leads to:
$$ f'(x) = x^{f(x)}\left(f'(x)\log x+\frac{f(x)}{x}\right)\tag{2}$$
hence:
$$ f'(x) = \frac{f(x)^2}{x\left(1-f(x)\log x\right)}\tag{3}$$
as you stated. We may also notice that:
$$ f(x)=\frac{W(-\log x)}{-\log x}\tag{4}$$
where $W$ is the Lambert W-function.


Q:

Odd Error in SharpZipLib -- Size was x, but I expected y

I'm getting an error when I use the SharpZipLib.  I have code that looks like
FastZip compressor = new FastZip();
compressor.CreateZip(outputFileName, currentWorkingDirectory, true, "");

Which seems to be correct.  However, I get a ZipException claiming that
size was 0, but I expected 54

I have no idea what that means.  Anyone have any insight, or a link to an API document of some sort?

A:

It turns out the issue was as follows.  I was trying to make a .zip file of all the items in a given directory, and place that .zip file IN the directory.  Apparently the way this library works, the .zip file is created, and then the directory is read in file-by-file, writing into the .zip file.  The error occured when it tried to add the .zip file itself to the zip!  It was probably denied access to the file or something at that point, resulting in the error above.  Simple fix was to create the .ZIP file in a different directory.


Q:

Add changed row number to mail body

I'm running Outlook in background. Using Excel 2010.
I want to do following:

send an automatic mail to defined persons
the body of the mail should contain the row and column number where the change happened
it should only work for cells in one specified column

I have the following:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim APP_OUTLOOK As Object
Dim MESSAGE As Object

Set APP_OUTLOOK = CreateObject("Outlook.Application")
Set MESSAGE = APP_OUTLOOK.CreateItem(0)

If Not Intersect(Target, Range("A1:A1048576")) Is Nothing Then
    With MESSAGE
        .To = "name.name@name.com"
        .Subject = ""
        .Body = "hey buddy, something has changed please have a look at cell: "
'the text should show: "hey buddy, something has changed please have a look at cell: A25000."
        .Display
    End With
End If
End Sub

It should only send the mail if the value in the cell is changed from "" to something or changed from a value to another value
It has to be dynamic because I can't specify an exact cell
The cell contains a date in the format "dd.mm.yy"

With the help of Zac I was able to solve my problem.
Here is the working code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim APP_OUTLOOK As Object
Dim MESSAGE As Object

Set APP_OUTLOOK = CreateObject("Outlook.Application")
Set MESSAGE = APP_OUTLOOK.CreateItem(0)

    If Not Intersect(Target, Range("A1:A1048576")) Is Nothing Then
        With MESSAGE
            .To = "name.name@name.com"
            .Subject = ""
            .Body = "hey buddy," & vbNewLine & vbNewLine & "the file has been modified" & vbNewLine & vbNewLine & "following cell has a new entry: " & Target.Address & vbNewLine & vbNewLine & "the new entry has the value " & Target.Text & vbNewLine & vbNewLine & "please check the excel file" & vbNewLine & vbNewLine & "best wishes," & vbNewLine & "me"
            .Display
        End With
    End If
End Sub

I have added Target.Text to display the value and Target.Address is to display the cell row and column.

A:

I haven't tested your code but it looks like it should work. To get the address of the cell changed, add Target.Address at the end of your .Body statement


Q:

WebkitAnimationEnd isn't firing. Can anyone see why?

I've recently started messing about with Javascript and can see some nice applications for the animation end listener in my job. I've got the following code and none of my listeners for the animation ending are firing. Can any one see any reason why either of the two listeners aren't working? I'm looking in Chrome.
http://jsfiddle.net/spacebeers/jkUyT/1/
#animationTest {
    width: 150px;
    text-align: center;
    display: block;
    padding: 20px;
    background: #000;
    color: #fff;
    border-bottom: 10px solid red;
    cursor: pointer;
            transition: border-bottom 0.5s linear; /* vendorless fallback */
         -o-transition: border-bottom 0.5s linear; /* opera */
        -ms-transition: border-bottom 0.5s linear; /* IE 10 */
       -moz-transition: border-bottom 0.5s linear; /* Firefox */
    -webkit-transition: border-bottom 0.5s linear; /*safari and chrome */
}

#animationTest:hover {
    border-bottom: 10px solid blue;
}

Hover over me

$('document').ready(function(){
    var animationTest = document.getElementById('animationTest');

    animationTest.addEventListener('webkitAnimationEnd', function(event){
            alert("Finished animation (listener)!");
            console.log("Finished animation (listener)!");
        }, false );

        $('#animationTest').bind("webkitAnimationEnd", function(event){
            alert("Finished animation (bind)!");
            console.log("Finished animation (bind)!");
        }, false );
});

A:

It should be webkitTransitionEnd
http://jsfiddle.net/jkUyT/3/


Q:

Combining two groups into one in regex

I am parsing IBM JVM thread dumps to extract various information. In current context the lock id on which the thread is waiting, and the id of the thread owning that lock. The lock id is consistent across all dumps and it takes form of hex value 0x000000000B0D9A20. But id of thread holding lock takes different values like hex id of the same form as lock id or something like <unknown> or <unowned>. It is lock owner's id that I am finding difficult to extract.
IBM thread dump specifies lock info with three clauses (as you can see in first screenshot):

Waiting on...
Blocked on...
Parked on...

I am performing OR operation on these clauses in regex.
I have written a generic method which accepts

thread dump line
regex to apply
Number of groups to return in a list

For example the call method1(threadDumpLine,regex,2) will apply regex on threadDumpLine and return the list [group1,group2] where group1 is a 1st group captured while group2 is 2nd one.
The first group need to be the lock id, which I am able to capture but second group can be either hex id or <unknown> or <unowned>. I am able to capture lock owner's id as 2nd group, but when it is <unowned> or <unknown> then it turns out to be 3rd group:

(above on regex101)
That was happening because I defined two separate groups to capture lock owner's id and <text>. So I tried to combine the two in one as follows:

(above on regex101)
How can I change the regex to capture as specified above with least possible steps?

A:

Try this:
(?:Blocked on|Parked on|Waiting on):[^@]*@(0x[0-9A-F]+) Owned by:[^<\n]*?(0x[0-9A-F]+|<.*?>)

output:
MATCH 1
    > 1.    [69-87]     `0x000000000B0D9A20`
    > 2.    [130-148]   `0x00000000846F4900`
MATCH 2
    > 1.    [288-306]   `0x000000000296F1E8`
    > 2.    [317-326]   `<unknown>`
MATCH 3
    > 1.    [466-484]   `0x0000000030A0C590`
    > 2.    [495-504]   `<unowned>`

demo


Q:

XSS Me Warnings - real XSS issues?

I've been using the free Firefox extension XSS Me from Security Compass to test for XSS problems. However, using what I understand to be safe filtering, XSS me still reports warnings. Are these accurate warnings or spurious?
Using the code below as a testcase:
<form method="post" action="">
<input type="text" name="param" value="<?php echo htmlentities($_POST['param'])?>">
<input type="submit">
</form>
<?php echo htmlentities($_POST['param'])?>

I run some nasties by hand but none of them are executed in the browser, and using Charles debugging proxy I can see that the response is encoded as expected.
However, XSS Me reports a number of warnings, as if it can see the unencoded string in the HTML source:
alt text http://img696.imageshack.us/img696/8850/xss.png
Looking in Charles at the same time, I can see the strings are encoded and should be safe e.g. <IMG SRC="jav ascript:document.vulnerable=true;">

Is there a vulnerability I haven't fixed?
Are these rogue warning messages?
And if so, is another Firefox extension (Firebug?) conflicting with XSS Me?

A:

I work at Security Compass and am the lead developer for the Exploit Me tools.
You're right that XSS Me is reporting a warning because these attack strings seem (to XSS Me) to have come back from the server completely unencoded. Another parser/JavaScript engine (like IE 6/7/8, Safari, or Chrome) might execute this code even though Firefox's parser and JavaScript engine don't.
XSS Me submits two requests:

One request where we detect exploitation using FireFox's JavaScript engine, which we call "errors"
A second request where we detect exploitation by simply grepping for the attack string in the HTML response page

The warning you're getting is caused by this second request.
I can help you get to the root cause of this issue if you can do the following:

Use packet sniffing software (i.e. Wireshark http://www.wireshark.org/) to detect the attack string rather than Charles. Sometimes proxies have a way of modifying or otherwise altering requests
In Firefox, can you go to tools->addons and disable all the extensions except XSS Me? That way you can be sure no other extension is changing the response (or request) before it gets to XSS Me.
View the source of the response page in Firefox to see if the unencoded string appears

If you'd like to send me an email (tom@securitycompass.com) with those results I'd be happy to help figure this out. If it's a bug in XSS Me (which I certainly hope not) then I can patch it and get a new build out.
Thanks,
Tom


Q:

Does the following statement imply convexity?

I apologize if this is a simple question or if this is not the right forum for it. Some background: the subadditivity of Shannon's entropy is credited to the concavity of $-x\log(x)$. So this got me thinking about the inverse:

Let $f:\mathbb{R}\to\mathbb{R}$ be such that for any $h>0$ and $y>x$ we have $$f(x+h)-f(x)\le f(y+h)-f(y)$$ Does this imply that $f$ is convex?

The statement is true if $f$ is continuous, but I have no idea about the general case. My gut feeling is that it's not and probably a counterexample would be some sort of a "hairy" function. I am looking for suggestions...

A:

Your proposed inequality is certainly true, and indeed an equality, whenever $f$ is additive, but one can build almost-arbitrarily-bad additive functions by considering a Hamel basis for $\mathbb R$ as a $\mathbb Q$-vector space.  Such functions (if not continuous) are bounded neither above nor below on any interval, hence not convex.
EDIT with more details:  As @LiviuNicolaescu points out, every convex function is continuous, so it suffices to produce an example of a discontinuous such function.  These exist (given choice, at least) in abundance, but here's one example.  Let $\mathcal B$ be a Hamel basis of $\mathbb R$ (i.e., a basis for $\mathbb R$ as a $\mathbb Q$-vector space) containing $1$, and let $x$ be any element of $\mathcal B \setminus \{1\}$.  Let $f$ be the unique $\mathbb Q$-linear extension to $\mathbb R$ of the characteristic function of $\{x\}$, viewed as a function $\mathcal B \to \mathbb R$.  Since $f$ satisfies $f(a + b) = f(a) + f(b)$ for all $a, b \in \mathbb R$ (by $\mathbb Q$-linearity), it satisfies your proposed inequality, and indeed makes it an equality.  Since $f$ vanishes on $\mathbb Q$ (because it vanishes at $1$ and is $\mathbb Q$-linear), if continuous, it would have to vanish everywhere; but it takes the value $1$ at $x$.

A:

Any linear function ($f(x+y)=f(x)+f(y)$)satisfies the above, and there are linear functions which are not convex assuming choice (using basis $\mathbb R/\mathbb Q$); measurability or local boundedness near a point excludes those.
Picking small $h$ (s.t. $x+h<y$) and using above inequality for $x+h$, $y$, $y+h$, $y-2x$, we get that above inequality implies convexity for the mean of two numbers ($2f(y)\le f(x)+f(y-2x)$) and that implies full convexity whenever $f$ is locally bounded near a point (which is equivalent to measurable in this context).


Q:

AWS SDK Java TransferManager limit download size

I am currently downloading S3 folders of which name matches with prefix_ to a local TMP_FOLDER via the following code snippet:
    TransferManager transferManager = TransferManagerBuilder.standard().withS3Client(s3Instance).build();
    MultipleFileDownload multipleFileDownload = transferManager.downloadDirectory(S3_BUCKET, "prefix_", TMP_FOLDER);
    multipleFileDownload.waitForCompletion();
    transferManager.shutdownNow();

The problem is that my machine runs out of disk space because those folders I am trying to download are huge (they contain many tiny text files but in sum the size of each one of the folders is up to several GiB).
So, my question is, is there a way to limit TransferManager or MultipleFileDownload just to download up to a specific size of data?
Ideally it should download the tiny files one by one checking if with the next file it surpasses the predefined limit or not, stopping if it does (this will avoid to have any incomplete file at the end)
(Of course I am supposing that none of the text files itself will be bigger that the limit established)

A:

You can use getProgress().getBytesTransferredMethod() to track the  file size that is being uploaded/downloaded from S3.When you reach the file limit you can pause/abort the S3 transfer and resume later. The following links might be helpful to you:

TransferManager
Using transferManager examples


Q:

de-serialze a byte[] that was serialzed with XmlSerializer

I have a byte[] that was serialized with the following code:
// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
    textWriter.Close();
}

problem is the data serialized looks like this:
iVBORw0KGgoAAAANSUhEUgAAAPAAAAFACAIAAAANimYEAAAAAXNSR0IArs4c6QAAAARnQU1BAACx......

when it gets stored in my database it looks like this:
0x89504E470D0A1A0A0000000D49484452000000F00000014008020000000D8A660400000001......

What is the difference, and how can I get the data from the disk back into a byte[]?

Note: the data is a Bitmap formatted as a png like this:
public byte[] ImageAsBytes
{
    get
    {
        if (_image != null)
        {
            MemoryStream stream = new MemoryStream();
            _image .Save(stream, ImageFormat.Png);
            return stream.ToArray();
        }
        else
        {
            return null;
        }
    }
    set
    {

        MemoryStream stream = new MemoryStream(value);
        _image = new Bitmap(stream);
    }
 }

A:

iVBORw0KGgoAAAANSUhEUgAAAPAAAAFACAIAAAANimYEAAAAA...

is base64 encoded representation of the binary data.
0x89504E470D0A1A0A0000000D49484452000000F000000140080...

is hexadecimal.
To get the data back from the disk use XmlSerializer and deserialize it back to the original object:
public static T DeserializeObject<T>(string filename)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var reader = XmlReader.Create(filename))
    {
        return (T)serializer.Deserialize(reader);
    }
}

But if you only have the base64 string representation you could use the FromBase64String method:
byte[] buffer = Convert.FromBase64String("iVBORw0KGgoAAANimYEAAAAA...");

Remark: make sure you always dispose disposable resources such as streams and text readers and writers. This doesn't seem to be the case in your SerializeObject<T> method nor in the getter and setter of the ImageAsBytes property.


Q:

Rails 3 and Rspec 2 turn off transactional fixtures for individual tests

I am in the process of upgrading my application to Rails 3.  I started using Rspec 2 with Rails 3.  I need to turn off transactional fixtures for some of my rspec tests.  Prior I used the following code in my model specs
 before(:all) do
    ActiveSupport::TestCase.use_transactional_fixtures = false
  end

  after(:all) do
    ActiveSupport::TestCase.use_transactional_fixtures = true
    clean_engine_database
  end

That now gives me the error:
 Failure/Error: ActiveSupport::TestCase.use_transactional_fixtures = false
     undefined method `use_transactional_fixtures=' for ActiveSupport::TestCase:Class

Is there a way to do this per test block in Rails 3 with Rspec 2?

A:

I'm looking for the answer to this question, came across this blog entry
It suggests to declare inside the describe block
describe "xxx" do
  self.use_transactional_fixtures = false
  ...

I tried it with Rails 3.0.7 with RSpec 2.6.3, and looks like working.


Q:

Choosing the second element with XML Parsing with Jquery

I tried to parse my XML file. It works, but i would like to parse only the second Song Element only. How I could do that ?
I tried to modify and change .each, but didn't worked...
XML file
<?xml version="1.0" encoding="utf-8"?>
 <Event status="happened">
  <Song title="GOODBYE (FEAT. LYSE)">
   <Artist name="FEDER">
   </Artist>
    <Info StartTime="23:10:54" ID="333" />
  </Song>
  <Song title="HOW YOU REMIND ME">
   <Artist name="NICKELBACK">
   </Artist>
    <Info StartTime="23:15:49" ID="295" />
  </Song>
 </Event>

The jQuery script

Thank you for your help !

A:

Get the song element by it's index using eq(). Then for each of the children you don't need an each since there is only one of each tag
  $.ajax({
    type: "GET",
    url: "Play.xml",
    dataType: "xml",
    success: function(xml) {

      var $song = $(xml).find('Song').eq(1),
        $info = $song.find('Info'),
        $artist = $song.find('Artist');

      var myObj = {
        title: $song.attr('title'),
        artist: $artist.attr('name'),
        time: $info.attr('StartTime'),
        id: $info.attr('ID')
      };

      $('.history').append("

" + myObj.time + " {" + myObj.id + "}

" + myObj.artist + "

" + myObj.title + "

");

    }
  });

DEMO


Q:

What is that gooey stuff from okra?

When cooking okra in a bit of water, the water becomes gooey.  What does the okra release that makes the water slimy?  Would the goo have other culinary uses (as an additive to thicken sauces or improve the texture of ice-creams)?

A:

The slime is called mucilage. It is around the seeds on the inside of the pod. It is made of protein and carbohydrates including fiber.
The mucilage is (as you alluded in your question) used for thickening gumbos and similar stews. Besides this, I've only ever seen it referred to as an annoyance and avoided by leaving the pod whole or dry cooking like frying.
I imagine there could be some creative halloween uses of mucilage but those would be off topic for this site. :)
EDIT
I was embarrassed that this answer was the accepted answer. I don't like answers that are (as mine was) "no that isn't possible because I've never heard of it." I was hoping someone else would shatter my world with some amazing new use of okra slime.
My curiosity piqued I used some of my copious free time while code compiled to do some more research.
I was able to find a couple of non traditional okra recipes that seemed interesting- such as candied okra slices or using the seeds from pickled okra as a caviar-like dish. But none of them took advantage of the mucilage- they all avoided it.
Carbohydrate based mucilage is used in ice cream and for other reasons. I found the following study about food health that did experiments with replacing milk fat with specifically okra mucilage (they refer to it as "okra gum")
Okra gum is acceptable milk-fat ingredient substitute in dessert
Two pertinent quotes:
"Although not currently produced by food manufacturers, previous studies produced fat-free chocolate bar cookies with acceptable sensory characteristics using okra gum as a fat ingredient substitute."
"Specifically, color and smell of frozen dairy desserts containing okra gum replacement for milk fat did not significantly differ from the control product. Texture, flavor, aftertaste, and overall acceptability ratings also averaged five or higher (neutral to like) for all products."
The study was about replacing milk fat where I think it would be more interesting as an enhancer as you asked in your question.
It seems perfectly reasonable that okra mucilage could find a place in more modern recipes.
But I couldn't find anyone doing it.

A:

While researching okra for an article (I'm a freelance writer) I came across this page by seridipity and thought I'd share what I've found (so far) in my quest: The mucilage in okra is a desired trait in West African (and, by extension, Brazilian, Caribbean and southeastern U.S.) cuisine. Baobab leaves also produce mucilage when cooked. It is used as a thickening agent in soups, stews and some stuffed okra pod dishes (also in South and Southeast Asia).
The only other use I've found is as a hair conditioner, which is a traditional Indian treatment that has become into some use in the United States.
There's some investigation into using it industrially as a low-friction lubricant.
Bryan Johnson


Q:

good tutorial and training material for ajax forms in drupal 7

I'm having some trouble to make an ajax-form work with drupal 7.
Besides the examples located in:
http://drupal.org/node/262422
can anyone suggest a good tutorial just for ajax-form?

A:

Well,
Looking for good tutorials and examples about ajax-form in drupal 7, i've found the following links:

https://drupal.stackexchange.com/ -> forum about drupal in the same style of stack overflow;
http://drupal.org/node/1043838 -> drupal examples
http://buildamodule.com/ -> a lot of videos about drupal (has some paid content, but also has free streaming videos)


Q:

How can I query a list of key value pairs using NHibernate ICriteria?

I have a class with a number of fields, one being an IList<KeyValuePair<string, string>>.
public class Foo
{
  public IList<KeyValuePair<string, string>> Bars { get; set; }
}

I'm using Fluent NHibernate and that particular field is mapped as follows:
HasMany(x => x.Bars).Component(Bar.Map);

and
public class BarMap : ComponentMap<KeyValuePair<string, string>>
    {
        public BarMap()
        {
            Map(x => x.Key);
            Map(x => x.Value);
        }

        public static void Map(CompositeElementPart<KeyValuePair<string, string>> part)
        {
            part.Map(x => x.Key);
            part.Map(x => x.Value);
        }
    }

Using the ICriteria API, I would like to be able to select all Foo where Bars contains a key value pair { X, Y }, and for the matching of X and Y values to be case insensitive. How can I do this?

A:

The way how to query IDictionary is in detail described here

NHibernate: Select item with entry in element bag or
NHibernate How do I query against an IList property?

and documented here
17.1.4.1. Alias and property references
Description                     Syntax                Example
A collection key                {[aliasname].key}     ORGID as {coll.key}
The id of an collection         {[aliasname].id}      EMPID as {coll.id}
The element of an collection    {[aliasname].element} XID as {coll.element}

So, we can do something like this
.Add(Restrictions.Eq("Bars.elements", searchedValue));


Q:

Form not being validated in javascript

I am trying to validate the user's input by linking a JS file to validate the inputs. However, when I click the submit button with erroneous data, the form is submitted and no validation error is given.
The form:
<form id="user_form" name="contactForm" action="#" method="GET" onsubmit="return validateForm();">

First name *

<input class="input_box" type="text" name="first_name" placeholder="Joe" />

<input id="submit_button" type="submit" name="submit" value="Submit"/>

</form>

And the JS I use to validate:
function validateForm(){

/* Validate the first name field of the form */
var fn = document.forms['contactForm'].first_name.value;

/* If the Name string is empty then return false and show warning. */
if (fn == ""){
    alert("First name must be filled out");
    document.forms['contactForm'].first_name.reset();
    return false;
}else if(fn.length <= 2){
    alert("Your first name must more than two characters");
    document.forms['contactForm'].first_name.reset();
    return false;
}

}

A:

I am not sure if you can call reset() on an element. I think you use that method on form object to clear all the fields. IE and FF doesn't seem to have a problem but Chrome seem to. As a result, chrome doesn't execute the javascript and submits the form always. Here is fiddle Form Submit and the updated code:
function validateForm() {

            /* Validate the first name field of the form */
            var fn = document.forms['contactForm'].first_name.value.trim();

            /* If the Name string is empty then return false and show warning. */
            if (fn == "") {
                alert("First name must be filled out");
                document.forms['contactForm'].first_name.value = '';//Removed reset
                return false;
            } else if (fn.length <= 2) {
                alert("Your first name must more than two characters");
                document.forms['contactForm'].first_name.value = '';//Removed reset
                return false;
            }
            return true;//Added
        }


Q:

Is it safe to let prosciutto and parmesan rise in bread dough overnight?

I tried an excellent prosciutto parmesan Italian loaf from a local bakery in Boston and I'd like to try making it myself. I have a great bread recipe (flour, water, yeast, salt) that has to sit at room temperature for 24 hours before baking. It's a no-knead bread, so you just pop the dough in a Dutch oven once it's risen. My question is, would it be okay to add the chunks of prosciutto and parm to the mixture before letting it rise overnight? I'm afraid if I add it in right before baking, the dough will get overworked and the bread will end up tough.

A:

Parmigiano and Prosciutto are made to be stored for long times. 24 hours out of the fridge are ok, and if you have any doubt, remember you're still cooking them in a very hot oven.
BTW cover them somehow in order to avoid any contamination from insects or similar.

A:

This is a very interesting question. Each of your 3 primary ingrediants, the dough, prosciuotto, and parmessian, can obviously be kept at room temperature for 24 hours. But I think combining them could create some problems.
The cheese and ham can sit outside of the fridge because they are very dry and are loaded with salt. This prevents bacteria from growing. But once you add them to the bread dough, they will absorb moisture, which may allow bacteria to grow. Fortunately, I believe there is a way around this.
You say that your bread recipe calls for the dough to sit for 24 hours. My guess is that this allows the dough to both rise and develope flavor. If you are going to include proscuitto and parmessan in the dough, allowing it to sit for 24 hours will further improve the flavor. (For example, I have seen some excellent chocolate chip cookie recipes call for letting the dough sit in the fridge overnight to allow the chocolate flavor to permeate the dough.)
Thus my answer is to let the dough sit in the fridge for 20 hours, and then raise it for 4 hours before baking. While in the fridge, your don't have to worry about bacteria growing on the ham or cheese, but your yeast cultures will survive. Pulling the bread out of the fridge 4 hours before you plan on baking it will allow the yeast to reactivate, and raise your bread dough.
Note: If your bread has not risen enough 1 hour before you plan on baking, put the dough and a bowl of boiling water in the oven (don't turn the oven on, obviously). The sauna you create will make the dough rise faster.


Q:

How to use PHP to display 50 random images from hundreds?

Possible Duplicate:
MySQL select 10 random rows from 600K rows fast

There are many varying examples across the web, but I am hoping someone has a solution that fits what I am looking for... Surely I cannot be the only one!
I am building a photography website and want to display 50+ image thumbnails on the landing page. The kicker is that I want it to display pictures randomly using PHP and without duplication. I also want each image to have its own, unique href and title params.
So, I have created a mySQL table that holds:
id image_path, image_href, image_title

I was figuring I would easily re-size the images on my own and put them in a folder in the root directory and then call it in the row image_path.
Does anyone have an idea how to do this the most efficient way? I have heard that rand() sucks when the database gets big. The database will grow to tens of thousands of images.
Let me know if you need/want clarification.
Thanks!!!
Edit: I may have come across the answer in my research, but I'm pretty new to PHP... :)

A:

You could query the database, sort the results by RAND() and select the top 50:
SELECT id, image_path, image_href, image_title
FROM table
ORDER BY RAND()
LIMIT 50

This guarantees no duplicate results unless your table itself has duplicates.
A faster method is outlined in this question: MySQL select 10 random rows from 600K rows fast


Q:

jq: Recursively rename keys

I have JSON with structure like what's shown below. "groups" may be nested under "items" to any arbitrary depth, so I need to write an expression that visits every "groups" and "items" property (or parent object); static paths won't do.
{
    "groups": [{
        "name": "group1",
        "items": [
            {
                "name": "item1",
                "groups": [
                    {
                        "name": "nestedGroup1",
                        "items": [
                            {
                                "name": "nestedItem1",
                                "groups": []
                            },{
                                "name": "nestedItem2",
                                "groups": []
                        }]
                    }
                ]
            },
            {
                "name": "item2",
                "groups": []
            }
        ]
    }]
}

How can I recursively rename all "groups" to say "newGroups" and "items" to "newItems"? If you break it down, I know I need to create new keys at each level and delete the old ones, but I'm having trouble expressing that. I've tried several variations on things like
.. |= if type == "object" and has("groups") then . + { newGroups: .groups } else . end

to perform the first step, but this results in copying the top-level "groups" value to "newGroups" while leaving the nested "groups" unchanged. The remaining values within "groups" then also get sibling "newGroups" with their nested "groups" with no "newGroups" siblings etc.
From observation, my understanding is that the paths generated by the .. operator are evaluated first, so the newly added key is never traversed. So then I tried variations on the above, replacing .. with recurse both with and without arguments, thinking that it would take the value produced by the RHS and feed it back in to the LHS, like this:
{ newGroups: .groups } | recurse |= if type == "object" and has("groups") then . + { newGroups: .groups } elif type == "object" and has("items") then . + { newItems: .items } else . end

The result is closer, but still so far away. The recursion kind of works, but only on keys that already existed; the new ones appended to the object are not visited.
I've also tried messing about with paths, getpath, and setpath to try to solve the problem that way but run into problems there as well. Please help me get unstuck!

A:

This is very well explained in jq - FAQ under recursive traversal using walk/1. I've used a standard implementation of walk/1 from jq-builtins page, since the version I have doesn't have it present by default.
From the documentation for walk/1 - recursively walks the input JSON entity, changing each encountered key, k, to (k|filter), where filter is the specified filter, which may be any jq expression.
I've used the following filter in my script
# Apply f to composite entities recursively, and to atoms
def walk(f):
  . as $in
  | if type == "object" then
      reduce keys_unsorted[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;

def translate_keys(f):
  walk( if type == "object" then
            with_entries( if .key | contains("groups") then
                             .key |= "newgroups"
                          elif .key | contains("items") then
                             .key |= "newitems"
                          else
                             . end
                        )
        else
            . end
      );

translate_keys(.)

and ran the script as
jq -f script.jq json

which produced the result you needed.


Q:

List using Nodes

we are learning about linked list using nodes and I'm not sure if i'm doing this right. We are suppose to just make a simple list but when I go to run the program, I'm getting nullpointerException pointing to showList() method but when I try to not use that method, then nothing prints out at all. Please any help is greatly appreciated.
 public class node {
      public int dataitems;
      public node next;
      node front;

public void initList(){
    front = null;
}

public node makeNode(int number){
    node newNode;
    newNode = new node();
    newNode.dataitems = number;
    newNode.next = null;
    return newNode;
}

public boolean isListEmpty(node front){
    boolean balance;
    if (front == null){
        balance = true;
    }
    else {
        balance = false;
    }
    return balance;

}

public node findTail(node front) {
    node current;
    current = front;
    while(current.next != null){
        //System.out.print(current.dataitems);
        current = current.next;

    } //System.out.println(current.dataitems);
    return current;
}

public void addNode(node front ,int number){
    node tail;
    if(isListEmpty(front)){
        front = makeNode(number);
    }
    else {
        tail = findTail(front);
        tail.next = makeNode(number);
    }
}

public void printNodes(int len){

    int j;
    for (j = 0; j < len; j++){
        addNode(front, j);
    }  showList(front);
}

public void showList(node front){
    node current;
    current = front;
    while ( current.next != null){
        System.out.print(current.dataitems);
        current = current.next;
    }
    System.out.println(current.dataitems);
}

public static void main(String[] args) {
     node x = new node();

     x.printNodes(50);
    }

       }

A:

The problem has to do with the variable scoping of your addNode method.
public void addNode(node front ,int number){
    node tail;
    if(isListEmpty(front)){
        front = makeNode(number); //reassigns the node front parameter
    }
    else {
        tail = findTail(front);
        tail.next = makeNode(number);
    }
}

Your assignment of "front" only assigns the makeNode(number) value to the local variable.  You need to use this.front to assign the makeNode(number) to the instance variable of your node class or refactor your variable name.
public void addNode(node front ,int number){
    node tail;
    if(isListEmpty(front)){
        //assigns a value to the member variable "front" of your node instance
        this.front = makeNode(number);
    }
    else {
        tail = findTail(front);
        tail.next = makeNode(number);
    }
}


Q:

Sorting ipod playlists by ID

Im trying to fetch all the user's playlists from iPod and sort them by playlist's ID.
This is what I did so far:
MPMediaQuery *allPlaylistsQuery = [MPMediaQuery playlistsQuery];
NSArray *allPlaylists = [allPlaylistsQuery collections];
NSArray *sortedPlaylists = [allPlaylists sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:MPMediaPlaylistPropertyPersistentID ascending:YES]]];

But I get exception:
'[<MPConcreteMediaPlaylist 0x14f38590> valueForUndefinedKey:]: this class is not key value coding-compliant for the key playlistPersistentID.'

So whats the easiest (and efficiet) why to do such sort?

A:

The reason for the exception is that MPMediaItem uses the method valueForProperty: to query property values, rather than valueForKey: which would make it KVC-compliant.  Why is doesn't support valueForKey: is a bit of a mystery to me as it would make the class much more useful, for example the code you supplied in your question would have worked I reckon.
Untested:
MPMediaQuery *allPlaylistsQuery = [MPMediaQuery playlistsQuery];
NSArray *allPlaylists = [allPlaylistsQuery collections];
NSArray *sorted = [allPlaylists sortedArrayUsingComparator:^(id obj1, id obj2) {
    NSNumber *id1 = [(MPMediaItem *)obj1 valueForProperty:MPMediaItemPropertyPersistentID];
    NSNumber *id2 = [(MPMediaItem *)obj2 valueForProperty:MPMediaItemPropertyPersistentID];
    return [id1 compare:id2];
}];


Q:

String splitting data.table column produces NAs

This is my first question on SO so let me know if it can be improved. I am working on a natural language processing project in R and am trying to build a data.table that contains test cases. Here, I build a much simplified example:
texts.dt <- data.table(string = c("one",
                                  "two words",
                                  "three words here",
                                  "four useless words here",
                                  "five useless meaningless words here",
                                  "six useless meaningless words here just",
                                  "seven useless meaningless words here just to",
                                  "eigth useless meaningless words here just to fill",
                                  "nine useless meaningless words here just to fill up",
                                  "ten useless meaningless words here just to fill up space"),
                       word.count = 1:10,
                       stop.at.word = c(0, 1, 2, 2, 4, 3, 3, 6, 7, 5))

This returns the data.table we will be working on:
                                                          string word.count stop.at.word
 1:                                                      one          1            0
 2:                                                two words          2            1
 3:                                         three words here          3            2
 4:                                  four useless words here          4            2
 5:                      five useless meaningless words here          5            4
 6:                  six useless meaningless words here just          6            3
 7:             seven useless meaningless words here just to          7            3
 8:        eigth useless meaningless words here just to fill          8            6
 9:      nine useless meaningless words here just to fill up          9            7
10: ten useless meaningless words here just to fill up space         10            5

In the real application, values in the stop.at.word column are determined at random (with an upper bound = word.count - 1). Also, strings are not ordered by length but that should not make a difference.
The code should add two columns inputand output, where inputcontains the substring from position 1 up to stop.at.wordand output contains the word that follows (single word), like so:
>desired_result
                                                          string word.count stop.at.word                                       input
     1:                                                      one          1            0
     2:                                                two words          2            1                                         two
     3:                                         three words here          3            2                                 three words
     4:                                  four useless words here          4            2                                four useless
     5:                      five useless meaningless words here          5            4              five useless meaningless words
     6:                  six useless meaningless words here just          6            2                                 six useless
     7:             seven useless meaningless words here just to          7            3                   seven useless meaningless
     8:        eigth useless meaningless words here just to fill          8            6   eigth useless meaningless words here just
     9:      nine useless meaningless words here just to fill up          9            7 nine useless meaningless words here just to
    10: ten useless meaningless words here just to fill up space         10            5          ten useless meaningless words here
             output
     1:
     2:       words
     3:        here
     4:       words
     5:        here
     6: meaningless
     7:       words
     8:          to
     9:        fill
    10:        just

Unfortunately what I get instead is this:
                                                      string word.count stop.at.word input output
 1:                                                      one          1            0
 2:                                                two words          2            1    NA     NA
 3:                                         three words here          3            2    NA     NA
 4:                                  four useless words here          4            2    NA     NA
 5:                      five useless meaningless words here          5            4    NA     NA
 6:                  six useless meaningless words here just          6            3    NA     NA
 7:             seven useless meaningless words here just to          7            3    NA     NA
 8:        eigth useless meaningless words here just to fill          8            6    NA     NA
 9:      nine useless meaningless words here just to fill up          9            7    NA     NA
10: ten useless meaningless words here just to fill up space         10            5  ten      NA

Notice the inconsistent results, with an empty string on row 1 and "ten" returned on row 10.
Here is the code I am using:
    texts.dt[, c("input", "output") := .(
        substr(string,
               1,
               sapply(gregexpr(" ", string),"[", stop.at.word) - 1),
        substr(string,
               sapply(gregexpr(" ", string),"[", stop.at.word),
               sapply(gregexpr(" ", string),"[", stop.at.word + 1) - 1)
    )]

I ran many tests and the substr instructions work well when I try individual strings in the console, but fail when applied to the data.table.
I suspect I am missing something related to scoping within data.table, but I haven't been using this package for long so I am quite confused.
I would greatly appreciate some assistance.
Thanks in advance!

A:

I would probably do
texts.dt[stop.at.word > 0, c("input","output") := {
  sp = strsplit(string, " ")
  list(
    mapply(function(p,n) paste(p[seq_len(n)], collapse = " "), sp, stop.at.word),
    mapply(`[`, sp, stop.at.word+1L)
  )
}]

# partial result
head(texts.dt, 4)

                    string word.count stop.at.word        input output
1:                     one          1            0           NA     NA
2:               two words          2            1          two  words
3:        three words here          3            2  three words   here
4: four useless words here          4            2 four useless  words

Alternately:
library(stringi)
texts.dt[stop.at.word > 0, c("input","output") := {
  patt = paste0("((\\w+ ){", stop.at.word-1, "}\\w+) (.*)")
  m    = stri_match(string, regex = patt)
  list(m[, 2], m[, 4])
}]

A:

An alternative to @Frank's mapply solution is using by = 1:nrow(texts.dt) with strsplit and paste:
library(data.table)
texts.dt[, `:=` (input = paste(strsplit(string, ' ')[[1]][1:stop.at.word][stop.at.word>0],
                               collapse = " "),
                 output = strsplit(string, ' ')[[1]][stop.at.word + 1]),
         by = 1:nrow(texts.dt)]

which gives:
> texts.dt
                                                      string word.count stop.at.word                                       input output
 1:                                                      one          1            0                                                one
 2:                                                two words          2            1                                         two  words
 3:                                         three words here          3            2                                 three words   here
 4:                                  four useless words here          4            2                                four useless  words
 5:                      five useless meaningless words here          5            4              five useless meaningless words   here
 6:                  six useless meaningless words here just          6            3                     six useless meaningless  words
 7:             seven useless meaningless words here just to          7            3                   seven useless meaningless  words
 8:        eigth useless meaningless words here just to fill          8            6   eigth useless meaningless words here just     to
 9:      nine useless meaningless words here just to fill up          9            7 nine useless meaningless words here just to   fill
10: ten useless meaningless words here just to fill up space         10            5          ten useless meaningless words here   just

Instead of using [[1]] you could also wrap the strsplit in unlist as follows: unlist(strsplit(string, ' ')) (instead of strsplit(string, ' ')[[1]]). This will give you the same result.

Two other options:
1) with the stringi package:
library(stringi)
texts.dt[, `:=`(input = paste(stri_extract_all_words(string[stop.at.word>0],
                                                     simplify = TRUE)[1:stop.at.word],
                              collapse = " "),
                output = stri_extract_all_words(string[stop.at.word>0],
                                                simplify = TRUE)[stop.at.word+1]),
         1:nrow(texts.dt)]

2) or an adaptation from this answer:
texts.dt[stop.at.word>0,
         c('input','output') := tstrsplit(string,
                                          split = paste0("(?=(?>\\s+\\S*){",
                                                         word.count - stop.at.word,
                                                         "}$)\\s"),
                                          perl = TRUE)
         ][, output := sub('(\\w+).*','\\1',output)]

which both give:
> texts.dt
                                                      string word.count stop.at.word                                       input output
 1:                                                      one          1            0                                          NA     NA
 2:                                                two words          2            1                                         two  words
 3:                                         three words here          3            2                                 three words   here
 4:                                  four useless words here          4            2                                four useless  words
 5:                      five useless meaningless words here          5            4              five useless meaningless words   here
 6:                  six useless meaningless words here just          6            3                     six useless meaningless  words
 7:             seven useless meaningless words here just to          7            3                   seven useless meaningless  words
 8:        eigth useless meaningless words here just to fill          8            6   eigth useless meaningless words here just     to
 9:      nine useless meaningless words here just to fill up          9            7 nine useless meaningless words here just to   fill
10: ten useless meaningless words here just to fill up space         10            5          ten useless meaningless words here   just

A:

dt[, `:=`(input  = sub(paste0('((\\s*\\w+){', stop.at.word, '}).*'), '\\1', string),
          output = sub(paste0('(\\s*\\w+){', stop.at.word, '}\\s*(\\w+).*'), '\\2', string))
   , by = stop.at.word][]
#                                                      string word.count stop.at.word
# 1:                                                      one          1            0
# 2:                                                two words          2            1
# 3:                                         three words here          3            2
# 4:                                  four useless words here          4            2
# 5:                      five useless meaningless words here          5            4
# 6:                  six useless meaningless words here just          6            3
# 7:             seven useless meaningless words here just to          7            3
# 8:        eigth useless meaningless words here just to fill          8            6
# 9:      nine useless meaningless words here just to fill up          9            7
#10: ten useless meaningless words here just to fill up space         10            5
#                                          input output
# 1:                                                one
# 2:                                         two  words
# 3:                                 three words   here
# 4:                                four useless  words
# 5:              five useless meaningless words   here
# 6:                     six useless meaningless  words
# 7:                   seven useless meaningless  words
# 8:   eigth useless meaningless words here just     to
# 9: nine useless meaningless words here just to   fill
#10:          ten useless meaningless words here   just

I'm not sure I understand the logic for output being nothing for first line, but the trivial fix, if indeed needed, is left to OP.


Q:

Wrapping youtube-dl into automator via applescript

I am hoping to make an automator application that prompts the user for input (i.e. youtube url), and downloads it using  youtube-dl (already installed via Homebrew). After this, I am trying to use the command youtube-dl URL_HERE -e which fetches the title of the video. I am hoping to make a notification that says "successfully downloaded TITLE_VIDEO" after it downloads successfully (if it downloads succesfully). I am using the "Run Applescript" command of automator.
This is all I've gotten so far:
display dialog "What is the youtube URL you want to download?" default answer ""
set answer to text returned of result

tell application "Terminal"
    activate
    do script with command "youtube-dl -f 140 " & answer
end tell

display notification "Successfully downloaded " & TITLE_HERE sound name "Blow"

I'm new to applescript, so only basic functions/ones that can be explained easily.
What I'm thinking is to do the terminal command youtube-dl URL_HERE -e which will return the title of the video (TITLE), and set that to a variable and then pass that variable to display notification

A:

Nice - a simple UI like that could be very useful in many situations!
Try this:
display dialog "URL to fetch?" default answer ""
set theUrl to (text returned of result)

--> get file
do shell script "cd /tmp/; /usr/local/bin/youtube-dl " & theUrl

--> get title
set theTitle to do shell script "/usr/local/bin/youtube-dl -e " & theUrl

display notification "Fetched " & theTitle sound name "Blow"
delay 1 --> avoid quit before notice

Unfortunately the youtube-dl script did not actually download the video when using the -e flag, (and an error occurred when trying to use the --exec CMD option).
Ended up just running the command twice; First download to /tmp, then get title.
Could also use the process id (pid) to track progress, etc.. :)
command 2>/dev/null & pid=$!

Update:
I could not get the output of certain commands through applescript, like 'nettop'. There are probably ways to fix it.
Here is my sloppy attempt at implementing a pid checking.. :)
set question to display dialog "URL to fetch?" default answer "" buttons {"Cancel", "Open in Browser", "Download"} default button 3
set pageURL to (text returned of result)
if pageURL is "" then return "No URL"
set choice to (button returned of question)

if choice is "Download" then
    try
        set pid to do shell script "cd /tmp/; /usr/local/bin/youtube-dl --newline " & pageURL & " > /tmp/vidstatus 2>&1 & echo $!"
        delay 1
        repeat while ((do shell script "kill -0 " & pid) is "") -- check if pid is still responding
            display dialog "Status: " & (do shell script "tail -n1 /tmp/vidstatus") -- display last line of output
        end repeat
    on error
        display dialog "Download complete!" -- eh, success, hopefully :)
    end try

else if choice is "Open in Browser" then
    try
        set videoURL to do shell script "/usr/local/bin/youtube-dl -g " & pageURL
        open location videoURL -- browser can stream and save file
    on error
        display dialog "Download aborted!"
    end try
end if


Q:

Buttons inside TAB not clickable/responding

I have done TABS in my app using TabHost.
one of the tabs has two buttons in it("button","anotherButton")
After I run my app I can see both tabs, but when I press on them nothing happens(they aren't even "clickable" when I press them.) And moreover, they don't respond to any listeners which I add to them.
Some code:
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <TabWidget android:id="@android:id/tabs"
            android:layout_width="fill_parent" android:layout_height="wrap_content" />
        <FrameLayout android:id="@android:id/tabcontent"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
            <AnalogClock android:id="@+id/tab1" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:layout_centerHorizontal="true" />

            <LinearLayout android:id="@+id/linearbuttonsview"
                android:orientation="vertical" android:layout_width="fill_parent"
                android:layout_height="fill_parent">

----pay attention here I decalred tab with two buttons !!! -----------------

                <Button android:id="@+id/button" android:layout_width="wrap_content"
                    android:onClick="onSemiButtonClick" android:layout_height="wrap_content" android:text="A semi-random button" />

                <Button android:id="@+id/anotherButton" android:layout_width="wrap_content"
                    android:layout_height="wrap_content" android:text="A semi-semi-random button"
                    android:scrollY="400px" />

            </LinearLayout>

            <ListView android:id="@+id/tablist" android:layout_width="fill_parent"

                android:layout_height="fill_parent" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

This is my code:
public class TabDemo extends Activity
{
    private ListView ls1;
    private Button semiButton;

    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        ls1 = new ListView(TabDemo.this);
        TabHost tabs = (TabHost) findViewById(R.id.tabhost);
        semiButton = (Button) findViewById(R.id.button);
        semiButton.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {

                int z = 0;
                z++;
            }

        });

        tabs.setup();

        // tab1
        TabSpec spec = tabs.newTabSpec("tag1");
        spec.setContent(R.id.tab1);
        spec.setIndicator("Clock");
        tabs.addTab(spec);

        // tab2
        spec = tabs.newTabSpec("tag2");
        spec.setContent(R.id.linearbuttonsview);
        spec.setIndicator("Button");
        tabs.addTab(spec);

        // tab3
        spec = tabs.newTabSpec("tag3");
        spec.setContent(new TabHost.TabContentFactory()
        {

            // we create a list view and give it as a reference to the the
            // content
            public View createTabContent(String tag)

            {

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        TabDemo.this, android.R.layout.simple_list_item_1,
                        new String[]
                        { "item1", "item2", "item3" });

                ls1.setAdapter(adapter);

                return ls1;

            }

        });
        spec.setIndicator("List");
        tabs.addTab(spec);
    }
}

A:

some change in your code (create each tab with different activity)
public class TabBarExample extends TabActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab);

        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tid1");

        firstTabSpec.setIndicator("First Tab").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second Tab").setContent(new Intent(this,SecondTab.class));

        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);

    }
}

FirstTab.java
public class FirstTab extends Activity {

    Button bt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabs1);

        bt = (Button) findViewById(R.id.button1);

        bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(FirstTab.this, "it's works", 2000).show();
            }
        });
    }
}

tab.xml
<TabHost android:layout_width="fill_parent"
    android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost">
    <LinearLayout android:id="@+id/LinearLayout01"
        android:orientation="vertical" android:layout_height="fill_parent"
        android:layout_width="fill_parent">
        <TabWidget android:id="@android:id/tabs"
            android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
        <FrameLayout android:id="@android:id/tabcontent"
            android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
    </LinearLayout>

</TabHost>

tab1.xml
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button android:text="Button" android:id="@+id/button1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>


Q:

NUnit: Is it possible to configure NUnit that a Test fails, if no Assert has executed

I am using NUnit. Is it possible to configure NUnit in a way, so that every UnitTest fails that does not call at least once an Assert-Method?
So I can prevent some cases of invalid UnitTests.

A:

Based on this discussion it does not appear to be possible. Admittedly this is from 3 years ago but I do not think the answer has changed.

Stated simply, there's no setting such as you are looking for. I
  recall that we discussed the possibility a long time ago on the old
  SourceForge mailing list and that the general opinion at the time was
  for an empty test to simply succeed. One reason is that some people
  were writing tests in which all the Asserts were conditional and
  didn't want to see a failure if none were applicable. Of course, the  biggest reason is that NUnit is oriented toward TDD, even if not
  exclusively. So the general community of users does not usually have a
  bunch of empty tests.

A 'bug' was created for adding support for a command line option to enable this feature but it does not appear to have any activity since 2013. I cannot see any corresponding issue on the nUnit Github though.


Q:

TypeError when trying to retrieve data from Microsoft CRM 2011 REST endpoint via JQuery ajax

I have the following javascript on the onChange event of a field:
$.ajax({
    type: "GET",
    dataType: "json",
    url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/rdi_departmentSet(guid'" + departmentId + "')",
    success: function (data, textStatus, xhr) {
        alert("Success");
    },
    error: function (xhr, textStatus, errorThrown) {
        alert(errorThrown.name + " - " + errorThrown.msg + " -- " + textStatus);
    }
});

The error callback is firing and I'm getting "TypeError - undefined -- error" in the alert. If I alert what I'm passing in as the url I can browse to it in IE and see the correct results. Any idea what's causing the TypeError?

A:

In this case, I think you're missing the "?" after the "rdi_departmentSet".
Additionally, I always use filter syntax like so: http://msdn.microsoft.com/en-us/library/gg309461.aspx#BKMK_filter


Q:

Solving a symmetric minimization problem with linear algebra?

I attempted this problem by using Lagrange multiplier, and it turned out easy to prove that $x_1=x_2=...=x_n=-\frac{1}{n}$ will minimize for $n\geq1$. However, this is a problem from a class dedicated to linear algebra, so I am wondering how would someone use concepts in linear algebra to get a same answer?

A:

$1 = \big \vert -1 \big \vert  = \big \vert \mathbf 1^T \mathbf x \big \vert \leq \big \Vert \mathbf 1 \big \Vert_2 \big \Vert \mathbf x\big \Vert_2 = \sqrt{n}\big \Vert \mathbf x\big \Vert_2$
so
$\frac{1}{\sqrt{n}} \leq \big \Vert \mathbf x\big \Vert_2$
with equality iff $\mathbf x \propto \mathbf 1$.  This is Cauchy-Schwarz, which people frequently first learn in a linear algebra class, so it seems like fair game for your linear algebra class.


Q:

Can English people understand my English even if I do not use English grammar, but just words, adverbs and context?

I would say English language is way too difficult because of its grammar.
For example, we have to conjugate many different tenses.
Other languages such as Vietnamese do not conjugate tenses.
For example, we say "I have been working for ABC for 10 years", "I went shopping yesterday", "She has just gone shopping"
In Vietnamese, we say "I work for ABC for 10 years", "I go shopping yesterday", "She just go shopping"
In Vietnamese, we rely on adverbs & context to differentiate tenses.
Can English people understand my English even if I do not use English grammar, but just words, adverbs and context?

A:

What is your goal?
If it's merely passing through as a tourist with your "Tarzan English", yes, people will understand you. They will possibly need some time to adjust to how you mangle the grammar ("I no can" instead "I cannot" is confusing at first, but for a native speaker, it's possible to adjust to it after some exposure).
If your goal is to be fluent or interact with English speakers on a professional/business level, then you will have to spend time learning proper grammar. And yes, learning grammar from books is not fun (for most people), but you can absorb grammar in a more fun way: reading books, watching movies, and speaking.
BTW, judging by your question, your (written) English is quite good, so you just need more practice speaking (and not being afraid of making mistakes and correcting them). This might be a cultural problem (in some cultures, making mistakes is "losing face", in others, you just shrug it off).
BTW2: English is my L3, and even after many years of living in the USA, I still sometimes do make mistakes, like not using articles correctly, or not using correct tenses, but those minor mistakes haven't prevented me from keeping a job (or answering questions on SO :-) )


Q:

How to protect against CSRF

How can I protect my website against Cross-Site Request Forgery attack?
I am visiting a "normal" website. (f.e. normal.php)
In the background it loads another website (f.e. victim.php/send_comment) where I'm already logged in.
The website fills the comment boxes of the victim.php with JS and automatically send the request.
In the web I always find the trick to use tokens against CSRF. But in this example, the website normal.php will get the token, when it loads the other website.
Am I misunderstanding how the token works? If not, how can i prevent my site from accepting this request?

A:

The whole idea of CSRF is that you can't get victim.php/send_comment without a token from a previous page you've visited.
You form a "chain" of requests from your initial login until you get there, where each request is authorized by the previous one - unless you intercept the login page, there should be no way to forge requests.
The easiest and safest way of doing this is just using a web framework that handles CSRF for you. Doing it by hand is probably unnecessary and error-prone.


Q:

AnimationDrawable is not working on 2.3.6 android version

AnimationDrawable is not working on 2.3.6 android version.
Is there support library for older verions?
My code is:
iv = (ImageView) findViewById(R.id.splashnew);
BitmapDrawable f0 = (BitmapDrawable)getResources().getDrawable(R.drawable.s1);
BitmapDrawable f1 = (BitmapDrawable)getResources().getDrawable(R.drawable.s2);
BitmapDrawable f2 = (BitmapDrawable)getResources().getDrawable(R.drawable.s3);
int dur = 850;
AnimationDrawable ad = new AnimationDrawable();
ad.addFrame(f0, dur);
ad.addFrame(f1, dur);
ad.addFrame(f2, dur);
ad.start();
ad.setOneShot(true);

A:

I got the answer:
You should start the animation in a runnable.
    iv.post(new Runnable(){
        public void run(){
             ad.start();
             ad.setOneShot(true); // use this if you want to run the animation only once
        }
    });


Q:

Constructing a NOT statement to parse XML

I'm trying to construct a statement which will parse my XML looking for all rows which do not contain the words 'HIDE' or 'CANCELLED' in the 'Title' field and do not have a blank 'Indexed' field.
So far I have tried this as a starting point, which I thought would filter out everything containing 'HIDE' and an empty Indexed field, but it does not work.
$(xml).find("Qry1:not(Title:contains('HIDE'), Indexed:contains(''))").each(function(){

Am I even close to being right here?

A:

How about a sequential approach?
$(xml).find("Qry1")
    .not(":has(Title:contains('HIDE'))")
    .not(":has(Title:contains('CANCELLED'))")
    .not(":has(Indexed:empty)")
    .each( /* ... */);

Try it:

var xml = "<root>\
  <Qry1>\
    <Title>HIDE</Title>\
    <Indexed>1</Indexed>\
  </Qry1>\
  <Qry1>\
    <Title>CANCELLED</Title>\
    <Indexed>1</Indexed>\
  </Qry1>\
  <Qry1>\
    <Title>I'm not indexed</Title>\
    <Indexed></Indexed>\
  </Qry1>\
  <Qry1>\
    <Title>Found Me!</Title>\
    <Indexed>1</Indexed>\
  </Qry1>\
</root>";

$(xml).find("Qry1")
    .not(":has(Title:contains('HIDE'))")
    .not(":has(Title:contains('CANCELLED'))")
    .not(":has(Indexed:empty)")
    .each(function () {
        var title = $(this).find("Title").text();
        $("
", {text: title}).appendTo("#target");
    });

You could also use .filter, like this:
$(xml).find("Qry1")
    .filter(function () {
        var $this = $(this),
            title = $this.find("Title").text(),
            indexed = $this.find("Indexed").text();

        return !(title === "HIDE" || title === "CANCELLED" || !indexed);
    })
    .each( /* ... */);


Q:

elementary Inequality.

Prove: $$ \Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big| \leq \frac{\pi}{12e}$$
Approach: we know:
$$ \Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big| \leq \int_1^\sqrt{3} \! \frac{|\sin(x)|}{e^x(x^2 +1)} \, \mathrm{d} x \leq \int_1^\sqrt{3} \! \frac{1}{e^x(x^2 +1)} \, \mathrm{d} x$$ Since $|\sin(x)|$ is bounded by 1 for every $x$. Can we keep estimating this integral, or should we just solve the last integral?
thanks.

A:

Use the fact $ 1<x<\sqrt{3} \implies e<e^x<e^{\sqrt{3}}$ and $|sin(x)|\leq 1$
$$\Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big|\leq \int_1^\sqrt{3} \! \frac{1}{e(x^2 +1)} \, \mathrm{d} x  \leq \frac{\pi}{12e}$$


Q:

Yet another frustum culling question

This one is kinda specific. If I'm to implement frustum culling in my game, that means each one of my cubes would need a bounding sphere. My first question is can I make the sphere so close to the edge of the cube that its still easily clickable for destroying and building? Frustum culling is easily done in XNA as I've recently learned, I just need to figure out where to place the code for the culling. I'm guessing in my method that draws all my cubes but I could be wrong. My camera class currently implements a bounding frustum which is in the update method like so
   frustum.Matrix = (view * proj);

Simple enough, as I can call that when I have a camera object in my class. This works for now, as I only have a camera in my main game class. The problem comes when I decide to move my camera to my player class, but I can worry about that later.
    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;
    CurrentContainmentType = CamerasFrustrum.Contains(cubes.CollisionSphere);

Can it really be as easy as adding those two lines to my foreach loop in my draw method? Or am I missing something bigger here?
UPDATE: I have added the lines to my draw methods and it works great!! So great infact that just moving a little bit removes the whole map. Many factors could of caused this, so I'll try to break it down.
    cubeBoundingSphere = new BoundingSphere(cubePosition, 0.5f);

This is in my cube constructor. cubePosition is stored in an array, The vertices that define my cube are factors of 1 ie: (1,0,1) so the radius should be .5. I least I think it should. The spheres are created every time a cube is created of course.
    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;

        foreach (Cube block in cube.cubes)
        {
            CurrentContainmentType = cam.frustum.Contains(cube.cubeBoundingSphere);

    ///more code here

     if (CurrentContainmentType != ContainmentType.Disjoint)
            {
                cube.Draw(effect);
            }

Within my draw method. Now I know this works because the map disappears, its just working wrong. Any idea on what I'm doing wrong?

A:

answer:
A bounding sphere for a cube will not have a radius of 0.5.  If the furthest point on a cube (a corner) has a model-local position of +/-(0.5,0.5,0.5) then the radius of the sphere must be equal to the length of that vector, or sqrt(0.5*0.5 + 0.5*0.5 + 0.5*0.5)=0.86602540378.  A radius of 0.5 will make a sphere that touches the midpoints of the cube's faces but which does not include the corners (a midpoint along the X axis would be at (+/-X,0,0) for instance putting it at radius sqrt(0.5*0.5 + 0*0 + 0*0)=0.5, which is too small to contain the whole cube).
unsolicited advice:
Really, though, bounding spheres are not ideal here.  You have cubes.  Why not use an AABB?  They will more tightly fit your objects (perfectly fit them, in fact) and you can easily enough do an AABB-Frustrum collision test.
Furthermore, if you're doing the Minecrafty type of rendering, don't render individual cubes.  You'll spend more time culling little cubes than you will rendering the actually visible ones.  Precompute a full mesh for each "chunk" of the world and simply recompute this mesh whenever you add or remove a block.  Now you can cull whole chunks, which will be relatively efficient, and rendering a whole chunk in a single draw call will be cheap and the built-in triangle clipping will be more than sufficient when only a part of a chunk is visible (most likely much quicker than culling each block).
To generate the mesh, do something like:
modify(chunk):
  clear chunk.mesh
  for each block in chunk.blocks:
    for each face in block.faces:
      if face is not adjacent to another block:
        add face to mesh

All your blocks' textures will need to be in a single atlas, of course.


Q:

Accessing a service inside an event subscriber

I have an event subscriber with Doctrine events. Inside that, I am trying to call a service I have registered. I've called it already from in a controller and it works there, but when I try to call it in my event subscriber I get an error:
Attempted to call method "get" on class "Path\To\My\Class".
Did you mean to call "getSubscribedEvents"?

The code looks like this:
$embedcode_service = $this->get('myproject.mynamespace.myfield.update');
$embedcode_service->refreshMyField($document);

Why can't I access my service inside this event subscriber? How can I get access to it?

A:

Cerad already answered I'm just going to elaborate:
Inject your service in your subscriber:
services:
    ...
    my.subscriber:
            class: Acme\SearchBundle\EventListener\SearchIndexerSubscriber
            # Service you want to inject
            arguments: [ @service_i_want_to_inject.custom ]
            tags:
                - { name: doctrine.event_subscriber, connection: default }
   ...

In the php code for your subscriber, assign the injected service to a class variable to be able to access it later on:
...
class SearchIndexerSubscriber implements EventSubscriber {

private $myservice;

public function __construct($myservice) {
    $this->myservice = $myservice;
}
...

Access the service methods through the class variable from any method within the subscriber:
$this->myservice->refreshMyField($document);

Listeners/subscribers in Symfony2
Services in Symfony2
Happy new year.


Q:

Understanding "this" in JQuery UI Widgets

Normally if I want to create a click event in JQuery I use the following syntax:
$("#test").on("click", function() { console.log($(this)); });
Here I can easily refer to the clicked element using the this keyword.
However in JQuery UI Widgets, it seems the format they want is:
this._on( $("li", this.list), {
      dblclick: function() {
        console.log$(this);
      }
});

The problem is, that JQuery UI uses this for the widget, and I'm unable to refer to the this that was clicked. Is there a special syntax I need?
The problem with using the normal JQuery method is that I can't my widget variables inside of it due to the this then referring to what was clicked.
Do I need to create a temporary placeholder variable to make this work (like var temp = this.myVar), or is there another workaround?

A:

the this keyword in the ui plugin is the element that the ui plugin is currently operating on. I would take a look on how to make a plugin here:
http://docs.jquery.com/Plugins/Authoring
That should give you the required information. However you can think of the ui-plugin code as a single iteration of the .each() method and the this keyword is the currently searched element in the list that you would get from say this $("p.findMe"). So in essence the this keyword is used so that another search of the DOM tree is not necessary.
The click function has some arguments that you can pass, such as the target element. take a look at this:
http://api.jquery.com/click/
Now specifically you will want to focus on the event object mentioned in the function overloads. By using function(event){} instead of function() in your dblclick you can use it to get the target element and all other information dealing with the event like its click location and parent elements.