问:
Make DataGridViewColumn non hideable
I'm using DataGridView control in my winforms project.
I have requirement to allow the user to edit this control: Hide/Show columns as he wants.
However there are some specific columns that users are not allowed to hide.
I was looking at all properties of DataGridViewColumn, it seems no one could help me out.

How can I make a  DataGridView column non hideable?

Edit:

Here is the full requirement that I'm trying to implement:

A user has the ability to right click a DataGridView and get new form listing all columns with check-boxes. So he can decide which column to hide and which column to keep by checking relative checkbox.
I'm looking for a flag or property for non hideable columns so I can remove it from listed (editable) columns.

I don't like to hard code non editable columns because I have to do the same think across the hole application. I have around 10 DataGridView.

答:
Like @Christopher said, you may have an array of columns to be set hidden and another for not allow hiding ones. You also have many DataGridViews, I suggest writing some public static methods then:

```<code>public static bool set_never_hide_column(DataGridView dgv, int[] col)
{
        try
        {
            foreach (DataGridViewColumn x in dgv.Columns)
            {
                if (col.Contains(dgv.Columns.IndexOf(x)))
                {
                    x.Tag = true;
                }
                else
                {
                    x.Tag = false;
                }
            }

            return true;
        }
        catch
        {
            return false;
        }
}

public static bool set_hide_column (DataGridView dgv, int[] col)
{
        try
        {
            foreach (DataGridViewColumn x in dgv.Columns)
            {
                if (col.Contains(dgv.Columns.IndexOf(x)) && (bool)x.Tag == false)
                {
                    x.Visible = false;
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
}
</code>```

set_never_hide_column use Tag property to set whether a column is hideable or not. This code will work based on column index.

So, for example, if I call set_never_hide_column(your_dgv, new int[] {0}) and set_hide_column(your_dgv, new int[] {0, 2}), only the third column will be hidden.

Title: Make DataGridViewColumn non hideable

Body:
Like @Christopher said, you may have an array of columns to be set hidden and another for not allow hiding ones. You also have many DataGridViews, I suggest writing some public static methods then:

public static bool set_never_hide_column(DataGridView dgv, int[] col)
{
        try
        {
            foreach (DataGridViewColumn x in dgv.Columns)
            {
                if (col.Contains(dgv.Columns.IndexOf(x)))
                {
                    x.Tag = true;
                }
                else
                {
                    x.Tag = false;
                }
            }

            return true;
        }
        catch
        {
            return false;
        }
}

public static bool set_hide_column (DataGridView dgv, int[] col)
{
        try
        {
            foreach (DataGridViewColumn x in dgv.Columns)
            {
                if (col.Contains(dgv.Columns.IndexOf(x)) && (bool)x.Tag == false)
                {
                    x.Visible = false;
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
}

set_never_hide_column use Tag property to set whether a column is hideable or not. This code will work based on column index.

So, for example, if I call set_never_hide_column(your_dgv, new int[] {0}) and set_hide_column(your_dgv, new int[] {0, 2}), only the third column will be hidden.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Numpy minimum like np.outer()
Maybe I'm just being lazy here, but let's say that I have two arrays, of length n and m, and I'd like a pairwise minimum of all of the elements of the two arrays compared against each other. For example:

```<code>a = [1,5,3]
b = [2,4]
cross_min(a,b)
= [[1,1],[2,4],[2,3]]
</code>```

This is similar to the behavior of np.outer(), except that instead of multiplying the two arrays, it computes the minimum of the two elements.

Is there an operation in numpy that does a similar thing?

I know that I can just run np.minimum() along b and stack the results together. I'm wondering if this is a well-known operation that I just don't know the name of.

答: You can use np.minimum.outer(a, b)

ContentLicense: CC BY-SA 3.0

Title: Numpy minimum like np.outer()

Body:
Maybe I'm just being lazy here, but let's say that I have two arrays, of length n and m, and I'd like a pairwise minimum of all of the elements of the two arrays compared against each other. For example:

a = [1,5,3]
b = [2,4]
cross_min(a,b)
= [[1,1],[2,4],[2,3]]

This is similar to the behavior of np.outer(), except that instead of multiplying the two arrays, it computes the minimum of the two elements.

Is there an operation in numpy that does a similar thing?

I know that I can just run np.minimum() along b and stack the results together. I'm wondering if this is a well-known operation that I just don't know the name of.

Body: You can use np.minimum.outer(a, b)


问:
unix timestamp datetime difference php
I am running into a strange problem with a discrepancy between a unix timestamp and the converted result.

Here is an example:

```<code>$timestamp = 1489132800;

echo date('l jS \of F Y h:i:s A', $timestamp);

// echo statement =  Friday 10th of March 2017 03:00:00 AM

// on unixtimestamp.com  this equates to 03/10/2017 @ 8:00am (UTC)
</code>```

Does anyone have any idea why there would be a 5 hour difference?  Does the date function rely on some internal time setting?

答:
This is because your converter returns the time in UTC, while your local timezone is 5 hours behind UTC.

You can check your current timezone via date_default_timezone_get() and change it with date_default_timezone_set().

You can also check with some onlineconverters that return your local time as well as UTC time: http://www.convertunixdate.com/

Title: unix timestamp datetime difference php

Body:
I am running into a strange problem with a discrepancy between a unix timestamp and the converted result.

Here is an example:

$timestamp = 1489132800;

echo date('l jS \of F Y h:i:s A', $timestamp);

// echo statement =  Friday 10th of March 2017 03:00:00 AM

// on unixtimestamp.com  this equates to 03/10/2017 @ 8:00am (UTC)

Does anyone have any idea why there would be a 5 hour difference?  Does the date function rely on some internal time setting?


问:
Skeletal animation with ASSIMP
I have been trying to implement skeletal animation in my own 3D openGL/c++ game engine using ASSIMP to import the models.

I think that the problem is caused by the calculation of the bone matrices, loaded as uniform variables in the shader because if I assign them to identities, the mesh is loaded in its bind pose.

These are the functions I use to initialize and calculate the ready bone matrices:

```<code>    void Joint::AddToSceneGraph(GameObject* root)
    {
        GameObject* parent = root->FindChild(m_name);
        //m_globalInverseMatrix = inverse(root->GetTransform().GetMatrix());
        parent->AddComponent(this);
        while (parent->GetParent() != root)
            parent = parent->GetParent();

        parent->GetTransform().SetParent(NULL); (1)
    }

    mat4 Joint::GetMatrix()
    {
        mat4 ans = /*m_globalInverseMatrix*/GetTransform().GetMatrix()*m_offsetMatrix;
        return ans;
    }
</code>```

Since I am trying to render the model in its bind pose I wont supply you the code of calculating animation matrices.

Some clarifications - I have a Transform class which has Transform* parent and whose GetMatrix() method calculates the matrix from the parent's one, scaling and translating vec3s and rotation quaternion so the relation between parent and child is taken in consideration. I assume that the parent's transform of the root joint has to be NULL thus its matrix - identity, which is the purpose of (1). Although I am not sure for this assumption, I am sure that the node with the root of the skeleton and the node, containing the meshes, are siblings.

Also I am not sure weather I should use m_globalInverseMatrix and furthermore what exactly is its purpose.

In general I think the main issue I have is misunderstanding of how ASSIMP calculates the offset matrix or so called inverse bind pose matrix and how to invert its effect. This issue results in the model looking "packed" in itself :

答:
From the docs in Assimp, the offset matrix of the bones transforms from the mesh space to the bone space.

I managed to render the bind pos with a hierarchy similar to yours (if I have not misunderstood, you have a root node with two children, one spawning the skeleton hierarchy and the other spawning the mesh). What you have to do is set the m_globalInverseMatrix to the inverse transform of the node containing the mesh. Then, each bone's transform is:

boneTransform = m_globalInverseMatrix * boneHierarchyTransforms * boneOffsetMatrix

where the boneHierarchyTransform comes from traversing the tree up to each bone node and the boneOffsetMatrix is the one you mention and I referred to in the first paragraph.

Title: Skeletal animation with ASSIMP

Body:
I have been trying to implement skeletal animation in my own 3D openGL/c++ game engine using ASSIMP to import the models.

I think that the problem is caused by the calculation of the bone matrices, loaded as uniform variables in the shader because if I assign them to identities, the mesh is loaded in its bind pose.

These are the functions I use to initialize and calculate the ready bone matrices:

    void Joint::AddToSceneGraph(GameObject* root)
    {
        GameObject* parent = root->FindChild(m_name);
        //m_globalInverseMatrix = inverse(root->GetTransform().GetMatrix());
        parent->AddComponent(this);
        while (parent->GetParent() != root)
            parent = parent->GetParent();

        parent->GetTransform().SetParent(NULL); (1)
    }

    mat4 Joint::GetMatrix()
    {
        mat4 ans = /*m_globalInverseMatrix*/GetTransform().GetMatrix()*m_offsetMatrix;
        return ans;
    }

Since I am trying to render the model in its bind pose I wont supply you the code of calculating animation matrices.

Some clarifications - I have a Transform class which has Transform* parent and whose GetMatrix() method calculates the matrix from the parent's one, scaling and translating vec3s and rotation quaternion so the relation between parent and child is taken in consideration. I assume that the parent's transform of the root joint has to be NULL thus its matrix - identity, which is the purpose of (1). Although I am not sure for this assumption, I am sure that the node with the root of the skeleton and the node, containing the meshes, are siblings.

Also I am not sure weather I should use m_globalInverseMatrix and furthermore what exactly is its purpose.

In general I think the main issue I have is misunderstanding of how ASSIMP calculates the offset matrix or so called inverse bind pose matrix and how to invert its effect. This issue results in the model looking "packed" in itself :


问:
NSTextView binding for complete: broken on macOS 10.12?
I've got an NSTextView subclass (Obj-C) that implements completion through the standard mechanism (implementing completionsForPartialWordRange:indexOfSelectedItem: and rangeForUserCompletion, etc.).  In the past, completion was invoked automatically by AppKit with either of two user actions: pressing command-. (command-period), or pressing esc (escape).  I have just switched to a new "late 2016" MacBook Pro, and simultaneously upgraded from 10.11 to 10.12.  Code completion no longer works in my app.  I just get a call to NSBeep() from deep in the responder chain, when nobody responds to those keypresses.  NSTextView's complete: method is never hit (says the debugger).

I suspect that this is because of a change Apple made.  I notice that the doc for complete: (at https://developer.apple.com/reference/appkit/nstextview/1449359-complete?language=objc) has changed; it used to say that complete: was triggered by esc, but now it says it is triggered by F5 (which also does not seem to work, on my machine, but function key mappings are always bizarre and incomprehensible, so who knows on that).

I did a little sleuthing by overriding doCommandForSelector: to just print the selector that AppKit is trying, and then calling super.  As it turns out, pressing esc now causes doCommandForSelector: to be called with cancelOperation: and cancel:, and pressing command-. now causes cancel:.  That makes some sense, since those keys are used to cancel out of panels, etc., but there is no panel involved here, no operation to cancel out of, etc.

My question is: what is the best way for me to simply get the old behavior back?  On 10.12 and later, in other words, I still want both esc and command-. to invoke complete: in my app.  I found Apple's doc on changing key bindings through a plist file, but that doesn't seem likely to be the right way to do it.  Maybe I should do a keyDown: override, but I thought those were discouraged because of complications regarding coalescing of key events, interpretation of key codes on international keyboards, etc.; my understanding is that that is generally too low a point to intervene in event processing.  Instead, I think I am supposed to modify the behavior of interpretKeyEvents: somehow, to bind the keys I want to complete:, but I can't figure out how to do that in code.

答: In Sierra, the key combination 'opt-esc' has replaced 'esc' as the standard binding for complete:. As you have observed, the unmodified 'esc' is now bound to cancelOperation:. For my apps, I'm documenting the new behaviour rather than overiding it as I suspect Apple has its reasons for making such an annoying change.


问:
Compare files byte by byte or read all bytes?
I came across this code http://support.microsoft.com/kb/320348 which made me wonder what would be the best way to compare 2 files in order to figure out if they differ.

The main idea is to optimize my program which needs to verify if any file is equal or not to create a list of changed files and/or files to delete / create.

Currently I am comparing the size of the files if they match i will go into a md5 checksum of the 2 files, but after looking at that code linked at the begin of this question it made me wonder if it is really worth to use it over creating a checksum of the 2 files (which is basically after you get all the bytes) ?

Also what other verifications should I make to reduce the work in check each file ?

答:
Read both files into a small buffer (4K or 8K) which is optimised for reading and then compare buffers in memory (byte by byte) which is optimised for comparing.

This will give you optimum performance for all cases (where difference is at the start, middle or the end).

Of course first step is to check if file length differs and if that's the case, files are indeed different..

ContentLicense: CC BY-SA 2.5


问:
Seaborn Distplot and Barplot
I have a dataframe that contains a column value of 'A','B','C','D'... This is just a grouping of some sorts. I wanted to produce a histogram with the column values vs its count.

```<code>import seaborn as sns
sns.distplot(dfGroupingWithoutNan['patient_group'])
</code>```

This produced an error:

```<code>TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code>```

I thought maybe because im not familiar with distplot, i'm not using it the right way. I was thinking, i can just pass a Series into it and it will be able to determine the counts for each values and display them in the histogram accordingly.

Anyway, i thought of other solution and this is what I came up with.

```<code>series1 = dfGroupingWithoutNan['patient_group'].value_counts()
dfPatientGroup = pd.DataFrame( {'levels' : series1.index, 'level_values' : series1.values})

sns.set_style("whitegrid")
sns.barplot(x="levels", y="level_values", data=dfPatientGroup)
</code>```

This time I was able to produce a plot of each values versus its count though using a bar plot.

I just wanted to ask, was there any other way to do this, like how it would have worked if i use the distplot? Also, do i really need to create a new dataframe just to have some sort of repository that holds the values and the count? I was thinking, wont it be possible for the distplot to determine the counts automatically without going through the hassle of creating a new dataframe?

答:
I would use a Counter to do this. The logic is very similar to what you are doing, but you don't need to create an extra dataframe:

```<code>from collections import Counter
cnt = Counter(dfGroupingWithoutNan.patient_group)
sns.barplot(x=cnt.keys(), y=cnt.values())
</code>```

I'm not aware of any solution that automatically handle string values in seaborn or matplotlib histograms.

Title: Seaborn Distplot and Barplot

Body:
I have a dataframe that contains a column value of 'A','B','C','D'... This is just a grouping of some sorts. I wanted to produce a histogram with the column values vs its count.

import seaborn as sns
sns.distplot(dfGroupingWithoutNan['patient_group'])

This produced an error:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

I thought maybe because im not familiar with distplot, i'm not using it the right way. I was thinking, i can just pass a Series into it and it will be able to determine the counts for each values and display them in the histogram accordingly.

Anyway, i thought of other solution and this is what I came up with.

series1 = dfGroupingWithoutNan['patient_group'].value_counts()
dfPatientGroup = pd.DataFrame( {'levels' : series1.index, 'level_values' : series1.values})

sns.set_style("whitegrid")
sns.barplot(x="levels", y="level_values", data=dfPatientGroup)

This time I was able to produce a plot of each values versus its count though using a bar plot.

I just wanted to ask, was there any other way to do this, like how it would have worked if i use the distplot? Also, do i really need to create a new dataframe just to have some sort of repository that holds the values and the count? I was thinking, wont it be possible for the distplot to determine the counts automatically without going through the hassle of creating a new dataframe?

Body:
I would use a Counter to do this. The logic is very similar to what you are doing, but you don't need to create an extra dataframe:

from collections import Counter
cnt = Counter(dfGroupingWithoutNan.patient_group)
sns.barplot(x=cnt.keys(), y=cnt.values())

I'm not aware of any solution that automatically handle string values in seaborn or matplotlib histograms.


问:
POST form data includes GET parameters used to generate the form
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

```<code><form action="./change" method="post">
    <p class="fieldName">Username (your email address):</p>
    <input type="text" name="thetaname"/>
    <p class="fieldName">Password:</p>
    <input type="password" name="thetaword"/>
    <p class="fieldName">Confirm Password:</p>
    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>
    <p class="errorMsg"></p>
    <br><br>
    <input type="submit" value="Submit"/>
</form>
</code>```

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?

答:
I cant say i completely understand your question but this might help;

If your using Java as your server side technology then please change the action attribute to (action="change") not (action="./change").

Body:
This one blew my mind for a while and now I think I know what it is.

I have this basic form that uses POST to submit the values.

<form action="./change" method="post">

Username (your email address):

    <input type="text" name="thetaname"/>

Password:

    <input type="password" name="thetaword"/>

Confirm Password:

    <input type="password" name="confirm"/>
    <input type="hidden" name="authkey" value="djj"/>

    <input type="submit" value="Submit"/>
</form>

and it submits to the same location that originally created the form. The issue seems to be that the form is originally created with a GET parameter on the URL and the form is a POST. When I look at the log, it looks like the GET parameter is included on the post and my Spring app is getting confused.

I'm using GET for the original because I'm emailing the link to the user. I'm using POST on the submit because I want to make sure the passwords and stuff are encrypted.

I'm running NGINX in front of Spring boot and it's returning an empty string from the submit.

The GET is listed as GET only on my method and POST as POST only on my method in my controller.

Ideas?


问:
Java boolean equations as parametar of function
Lets take a look at my program. That have some imaginary .txt file with car models.

```<code>public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}
</code>```

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

```<code>public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}
</code>```

答:
If you are on Java 8, you could use the Stream API with a Predicate:

```<code>cars.stream()
    .filter(c -> c.getModel().equals(someModel))
    .forEach(c -> System.out.println("Hit!"));
</code>```

The argument of the Stream.filter method is a Predicate that is expressed as a lambda expression, in this case car -> someModel.equals(car.getModel()).

You can change the lambda expression to match your second example:

```<code>cars.stream()
    .filter(c -> !c.getModel().equals(someModel))
    .forEach(c -> System.out.println("Hit!"));
</code>```

The way to abstract this to a method is to pass the list, the predicate, and if you want, a Consumer that will take some action on the matching elements. Here's some code that you might use as a starting point:

```<code>public static void handleCars(
        List<Car> cars,
        Predicate<Car> condition,
        Consumer<Car> action) {

    cars.stream().filter(condition).forEach(action);
}
</code>```

You can read that line of code as: stream the list of cars, filter only the cars that match the given condition and, for each one of them, take the given action.

And you can invoke the handleCars method as follows:

```<code>handleCars(
    cars,
    c -> c.getModel().equals(someModel),
    c -> System.out.println("Car with model " + someModel + " hit!"));
</code>```

Or:

```<code>handleCars(
    cars,
    c -> c.getBrand().toLowerCase().contains("mercedes"), // assume brand is String
    c -> System.out.println("Mercedes model found: " + c.getModel()));
</code>```

As you see, the predicates and the consumers can be as complex as you need.

Body:
Lets take a look at my program. That have some imaginary .txt file with car models.

public class Car {
    private String model;

    public String getModel() {
        return this.model;
    }
}

public class Main {
    public static void Main(String[] args) {
        ArrayList<Car> cars = loadCars(path); //imaginary func and file
        String someModel = generateSomeModel(); //imaginart func

        for (Car c : cars)
            if (c.getModel.equals(someModel))
                System.out.println("Hit!");

        for (Car c : cars)
            if (!c.getModel.equals(someModel))
                System.out.println("Hit!");

    }
}

Lets suppose that I have to go through my cars list a 100 times and compare them in if statement for some different attributes every time, that means I  will have to write 100 different for loops that will be 90% same. Is there a way to write a function that will take as a parametar Boolean equation? Something like this.

public static void printCars(Boolean equation) {
    for (Car c : cars)
        if (Boolean equation)
            System.out.println("Hit!");
}

Body:
If you are on Java 8, you could use the Stream API with a Predicate:

cars.stream()
    .filter(c -> c.getModel().equals(someModel))
    .forEach(c -> System.out.println("Hit!"));

The argument of the Stream.filter method is a Predicate that is expressed as a lambda expression, in this case car -> someModel.equals(car.getModel()).

You can change the lambda expression to match your second example:

cars.stream()
    .filter(c -> !c.getModel().equals(someModel))
    .forEach(c -> System.out.println("Hit!"));

The way to abstract this to a method is to pass the list, the predicate, and if you want, a Consumer that will take some action on the matching elements. Here's some code that you might use as a starting point:

public static void handleCars(
        List<Car> cars,
        Predicate<Car> condition,
        Consumer<Car> action) {

    cars.stream().filter(condition).forEach(action);
}

You can read that line of code as: stream the list of cars, filter only the cars that match the given condition and, for each one of them, take the given action.

And you can invoke the handleCars method as follows:

handleCars(
    cars,
    c -> c.getModel().equals(someModel),
    c -> System.out.println("Car with model " + someModel + " hit!"));

Or:

handleCars(
    cars,
    c -> c.getBrand().toLowerCase().contains("mercedes"), // assume brand is String
    c -> System.out.println("Mercedes model found: " + c.getModel()));

As you see, the predicates and the consumers can be as complex as you need.


问:
Filterrific: ERROR: undefined method `empty?' for nil:NilClass
Having trouble getting the filterrific gem to work. I am getting the error "ERROR: undefined method `empty?' for nil:NilClass", it seems like the problem comes from the f.select in my form.

I have attached the relevant code in this link: https://github.com/jhund/filterrific/issues/26

I have been trying to get this gem to work all day with no luck. Great documentation, but just can't get it to work. Would appreciate any pointers.

[STACK TRACE]

```<code>NoMethodError - undefined method `empty?' for nil:NilClass:
  actionview (4.1.4) lib/action_view/helpers/tags/select.rb:36:in `grouped_choices?'
  actionview (4.1.4) lib/action_view/helpers/tags/select.rb:20:in `render'
  actionview (4.1.4) lib/action_view/helpers/form_options_helper.rb:165:in `select'
  actionview (4.1.4) lib/action_view/helpers/form_options_helper.rb:779:in `select'
   () Users/erikchan/Workspace/productchamp/app/views/projects/_admin_angels.html.erb:9:in `block in _app_views_projects__admin_angels_html_erb___4541097495823350739_70281797177960'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:38:in `block in capture'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:200:in `with_output_buffer'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:38:in `capture'
  actionview (4.1.4) lib/action_view/helpers/form_helper.rb:434:in `form_for'
  filterrific (1.4.2) lib/filterrific/action_view_extension.rb:18:in `form_for'
   () Users/erikchan/Workspace/productchamp/app/views/projects/_admin_angels.html.erb:6:in `_app_views_projects__admin_angels_html_erb___4541097495823350739_70281797177960'
  actionview (4.1.4) lib/action_view/template.rb:145:in `block in render'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:339:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:143:in `render'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:306:in `render_partial'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:279:in `block in render'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:278:in `render'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:47:in `render_partial'
  actionview (4.1.4) lib/action_view/helpers/rendering_helper.rb:35:in `render'
   () Users/erikchan/Workspace/productchamp/app/views/projects/show_dashboard.html.erb:34:in `_app_views_projects_show_dashboard_html_erb___2410799250841293991_70281799504140'
  actionview (4.1.4) lib/action_view/template.rb:145:in `block in render'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:339:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:143:in `render'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:55:in `block (2 levels) in render_template'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:54:in `block in render_template'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:62:in `render_with_layout'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:53:in `render_template'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:17:in `render'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:42:in `render_template'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:23:in `render'
  actionview (4.1.4) lib/action_view/rendering.rb:99:in `_render_template'
  actionpack (4.1.4) lib/action_controller/metal/streaming.rb:217:in `_render_template'
  actionview (4.1.4) lib/action_view/rendering.rb:82:in `render_to_body'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:32:in `render_to_body'
  actionpack (4.1.4) lib/action_controller/metal/renderers.rb:32:in `render_to_body'
  actionpack (4.1.4) lib/abstract_controller/rendering.rb:25:in `render'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:16:in `render'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:41:in `block (2 levels) in render'
  activesupport (4.1.4) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
   () Users/erikchan/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
  activesupport (4.1.4) lib/active_support/core_ext/benchmark.rb:12:in `ms'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:41:in `block in render'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:84:in `cleanup_view_runtime'
  activerecord (4.1.4) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:40:in `render'
  remotipart (1.2.1) lib/remotipart/render_overrides.rb:14:in `render_with_remotipart'
  actionpack (4.1.4) lib/action_controller/metal/mime_responds.rb:258:in `respond_to'
   () Users/erikchan/Workspace/productchamp/app/controllers/projects_controller.rb:118:in `show_dashboard'
  actionpack (4.1.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.4) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.1.4) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:136:in `process'
  actionview (4.1.4) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.1.4) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal.rb:232:in `block in action'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:50:in `call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:678:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/error_collector.rb:55:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/agent_hooks.rb:32:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/browser_monitoring.rb:27:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/flash.rb:254:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.1.4) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
  activerecord (4.1.4) lib/active_record/migration.rb:380:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:82:in `run_callbacks'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:57:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.4) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `call'
  quiet_assets (1.0.3) lib/quiet_assets.rb:23:in `call_with_quiet_assets'
  actionpack (4.1.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.4) lib/rails/engine.rb:514:in `call'
  railties (4.1.4) lib/rails/application.rb:144:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  unicorn (4.8.3) lib/unicorn/http_server.rb:576:in `process_client'
  unicorn (4.8.3) lib/unicorn/http_server.rb:670:in `worker_loop'
  newrelic_rpm (3.7.3.204) lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:22:in `block (4 levels) in <top (required)>'
  unicorn (4.8.3) lib/unicorn/http_server.rb:525:in `spawn_missing_workers'
  unicorn (4.8.3) lib/unicorn/http_server.rb:140:in `start'
  unicorn-rails (2.2.0) lib/unicorn_rails.rb:33:in `run'
  rack (1.5.2) lib/rack/server.rb:264:in `start'
  railties (4.1.4) lib/rails/commands/server.rb:69:in `start'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:81:in `block in server'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:76:in `server'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:40:in `run_command!'
  railties (4.1.4) lib/rails/commands.rb:17:in `<top (required)>'
   () Users/erikchan/Workspace/productchamp/bin/rails:8:in `<top (required)>'
  spring (1.1.3) lib/spring/client/rails.rb:27:in `call'
  spring (1.1.3) lib/spring/client/command.rb:7:in `call'
  spring (1.1.3) lib/spring/client.rb:26:in `run'
  spring (1.1.3) bin/spring:48:in `<top (required)>'
  spring (1.1.3) lib/spring/binstub.rb:11:in `<top (required)>'
   () Users/erikchan/Workspace/productchamp/bin/spring:16:in `<top (required)>'
   () rails:3:in `<main>'
</code>```

答:
I know it's been a long time, but if anyone is still wondering about the answer then please find it below:

It seems the error was due to a bug in the demo app, this was fixed and was committed to the demo app. Please find the answer in the below link (it is the same link as mentioned above)

https://github.com/jhund/filterrific/issues/26

Body:
Having trouble getting the filterrific gem to work. I am getting the error "ERROR: undefined method `empty?' for nil:NilClass", it seems like the problem comes from the f.select in my form.

I have attached the relevant code in this link: https://github.com/jhund/filterrific/issues/26

I have been trying to get this gem to work all day with no luck. Great documentation, but just can't get it to work. Would appreciate any pointers.

[STACK TRACE]

NoMethodError - undefined method `empty?' for nil:NilClass:
  actionview (4.1.4) lib/action_view/helpers/tags/select.rb:36:in `grouped_choices?'
  actionview (4.1.4) lib/action_view/helpers/tags/select.rb:20:in `render'
  actionview (4.1.4) lib/action_view/helpers/form_options_helper.rb:165:in `select'
  actionview (4.1.4) lib/action_view/helpers/form_options_helper.rb:779:in `select'
   () Users/erikchan/Workspace/productchamp/app/views/projects/_admin_angels.html.erb:9:in `block in _app_views_projects__admin_angels_html_erb___4541097495823350739_70281797177960'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:38:in `block in capture'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:200:in `with_output_buffer'
  actionview (4.1.4) lib/action_view/helpers/capture_helper.rb:38:in `capture'
  actionview (4.1.4) lib/action_view/helpers/form_helper.rb:434:in `form_for'
  filterrific (1.4.2) lib/filterrific/action_view_extension.rb:18:in `form_for'
   () Users/erikchan/Workspace/productchamp/app/views/projects/_admin_angels.html.erb:6:in `_app_views_projects__admin_angels_html_erb___4541097495823350739_70281797177960'
  actionview (4.1.4) lib/action_view/template.rb:145:in `block in render'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:339:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:143:in `render'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:306:in `render_partial'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:279:in `block in render'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/partial_renderer.rb:278:in `render'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:47:in `render_partial'
  actionview (4.1.4) lib/action_view/helpers/rendering_helper.rb:35:in `render'
   () Users/erikchan/Workspace/productchamp/app/views/projects/show_dashboard.html.erb:34:in `_app_views_projects_show_dashboard_html_erb___2410799250841293991_70281799504140'
  actionview (4.1.4) lib/action_view/template.rb:145:in `block in render'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:339:in `instrument'
  actionview (4.1.4) lib/action_view/template.rb:143:in `render'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:55:in `block (2 levels) in render_template'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:54:in `block in render_template'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:62:in `render_with_layout'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:53:in `render_template'
  actionview (4.1.4) lib/action_view/renderer/template_renderer.rb:17:in `render'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:42:in `render_template'
  actionview (4.1.4) lib/action_view/renderer/renderer.rb:23:in `render'
  actionview (4.1.4) lib/action_view/rendering.rb:99:in `_render_template'
  actionpack (4.1.4) lib/action_controller/metal/streaming.rb:217:in `_render_template'
  actionview (4.1.4) lib/action_view/rendering.rb:82:in `render_to_body'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:32:in `render_to_body'
  actionpack (4.1.4) lib/action_controller/metal/renderers.rb:32:in `render_to_body'
  actionpack (4.1.4) lib/abstract_controller/rendering.rb:25:in `render'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:16:in `render'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:41:in `block (2 levels) in render'
  activesupport (4.1.4) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
   () Users/erikchan/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
  activesupport (4.1.4) lib/active_support/core_ext/benchmark.rb:12:in `ms'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:41:in `block in render'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:84:in `cleanup_view_runtime'
  activerecord (4.1.4) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:40:in `render'
  remotipart (1.2.1) lib/remotipart/render_overrides.rb:14:in `render_with_remotipart'
  actionpack (4.1.4) lib/action_controller/metal/mime_responds.rb:258:in `respond_to'
   () Users/erikchan/Workspace/productchamp/app/controllers/projects_controller.rb:118:in `show_dashboard'
  actionpack (4.1.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.4) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.1.4) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:136:in `process'
  actionview (4.1.4) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.1.4) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal.rb:232:in `block in action'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:50:in `call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:678:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/error_collector.rb:55:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/agent_hooks.rb:32:in `call'
  newrelic_rpm (3.7.3.204) lib/new_relic/rack/browser_monitoring.rb:27:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/flash.rb:254:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.1.4) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
  activerecord (4.1.4) lib/active_record/migration.rb:380:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:82:in `run_callbacks'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.0.0) lib/better_errors/middleware.rb:57:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.4) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `call'
  quiet_assets (1.0.3) lib/quiet_assets.rb:23:in `call_with_quiet_assets'
  actionpack (4.1.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.4) lib/rails/engine.rb:514:in `call'
  railties (4.1.4) lib/rails/application.rb:144:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  unicorn (4.8.3) lib/unicorn/http_server.rb:576:in `process_client'
  unicorn (4.8.3) lib/unicorn/http_server.rb:670:in `worker_loop'
  newrelic_rpm (3.7.3.204) lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:22:in `block (4 levels) in <top (required)>'
  unicorn (4.8.3) lib/unicorn/http_server.rb:525:in `spawn_missing_workers'
  unicorn (4.8.3) lib/unicorn/http_server.rb:140:in `start'
  unicorn-rails (2.2.0) lib/unicorn_rails.rb:33:in `run'
  rack (1.5.2) lib/rack/server.rb:264:in `start'
  railties (4.1.4) lib/rails/commands/server.rb:69:in `start'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:81:in `block in server'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:76:in `server'
  railties (4.1.4) lib/rails/commands/commands_tasks.rb:40:in `run_command!'
  railties (4.1.4) lib/rails/commands.rb:17:in `<top (required)>'
   () Users/erikchan/Workspace/productchamp/bin/rails:8:in `<top (required)>'
  spring (1.1.3) lib/spring/client/rails.rb:27:in `call'
  spring (1.1.3) lib/spring/client/command.rb:7:in `call'
  spring (1.1.3) lib/spring/client.rb:26:in `run'
  spring (1.1.3) bin/spring:48:in `<top (required)>'
  spring (1.1.3) lib/spring/binstub.rb:11:in `<top (required)>'
   () Users/erikchan/Workspace/productchamp/bin/spring:16:in `<top (required)>'
   () rails:3:in `'


问:
Django- Multiple languages on the same site
My issue has to do with a Django site running using one language, and using specific languages for specific apps

My example is:

I want to run a 'pt-pt' (Portuguese- Portugal) Django site. In it, I'm using a 3rd party App that has pt-BR (Portuguese- Brazil) as an available language, but no pt-pt translation. Lacking, pt-pt, pt-BR would be better than English.

I can set the language as:

```<code>#settings.py...

LANGUAGE_CODE = 'pt-pt'
</code>```

But then the site Admin uses pt-pt and the App uses English (undesirable).

If I set it to pt-BR I'll get pt-BR on the site (undesirable) and pt-BR on the App.

So I read Django's Docs again and tried the Languages setting

```<code>#settings.py...

LANGUAGE_CODE = 'pt'

from django.utils.translation import ugettext_lazy as _
LANGUAGES = (
    ('pt', _('Portuguese')),
    ('pt-br', _('Brazilian Portuguese')),
)
</code>```

to no avail (nothing changed). Is there a way to do this?

答:
I believe your best option is to copy the locale files of the pt-BR app to the project root locale directory. Then rename the folder from pt-BR to pt-pt and when you browse the site as pt-pt it will include that particular locale file.

Another option would be to use activate('pt-BR') in the pt-BR app but that would not be very conveniant.

Body:
My issue has to do with a Django site running using one language, and using specific languages for specific apps

My example is:

I want to run a 'pt-pt' (Portuguese- Portugal) Django site. In it, I'm using a 3rd party App that has pt-BR (Portuguese- Brazil) as an available language, but no pt-pt translation. Lacking, pt-pt, pt-BR would be better than English.

I can set the language as:

#settings.py...

LANGUAGE_CODE = 'pt-pt'

But then the site Admin uses pt-pt and the App uses English (undesirable).

If I set it to pt-BR I'll get pt-BR on the site (undesirable) and pt-BR on the App.

So I read Django's Docs again and tried the Languages setting

#settings.py...

LANGUAGE_CODE = 'pt'

from django.utils.translation import ugettext_lazy as _
LANGUAGES = (
    ('pt', _('Portuguese')),
    ('pt-br', _('Brazilian Portuguese')),
)

to no avail (nothing changed). Is there a way to do this?


问:
Change button text with Javascript?
I'm trying to use Javascript to change the button display text (in this case, "Push Here") using this code:

```<code>var button_list = document.getElementsByTagName('button');
var button = button_list[0];

<button class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>
</code>```

However, I can't change it with button.value = "New Text". What am I doing wrong?

答:
```<code> var button = document.getElementsByName('button')
</code>```

It needs to set a button name, now I'll show you

```<code><button name="button" class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>
</code>```

I recommend you use a different name

```<code> var button = document.getElementsByName('mybutton_1')
</code>```

and html

```<code><button name="mybutton_1" class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>
</code>```

Now you can use it

```<code>button.value = "New Text"
</code>```

look not getElementsByTagName but getElementsByName

Title: Change button text with Javascript?

Body:
I'm trying to use Javascript to change the button display text (in this case, "Push Here") using this code:

var button_list = document.getElementsByTagName('button');
var button = button_list[0];

<button class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>

However, I can't change it with button.value = "New Text". What am I doing wrong?

Body:
 var button = document.getElementsByName('button')

It needs to set a button name, now I'll show you

<button name="button" class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>

I recommend you use a different name

 var button = document.getElementsByName('mybutton_1')

and html

<button name="mybutton_1" class="btn-primary" id="btn-header-example-cs" data-toggle="modal" data-url="" data-options="" style="display: inline-block;">Push Here</button>

Now you can use it

button.value = "New Text"

look not getElementsByTagName but getElementsByName


问:
Putting image in table using innerHTML (Javascript / Html)
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
                } else if {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

答:
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:

```<code>if (i === 1 && j === 2) {...
</code>```

If you want the whole 2nd row with the same image in each cell then it should be:

```<code>if (i === 1) {...
</code>```

If you want a entire 3rd column to have the same image then it would be:

```<code>if (j === 2) {...
</code>```

If it's a different image for every cell, then name each file by table coordinates like this...

```<code>img1-2.png
</code>```

...then change the string that renders an image inside a cell as:

```<code> table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
</code>```

Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...

```<code> table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`
</code>```

... and the array would be something like this:

```<code>  var array = [
      ['rt','AD','1000.png','uy','ii'],
      ['rt','AD','1001.png','uy','ii'],
      ['rt','AD','1002.png','uy','ii']
    ];
</code>```

BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.

Also you'll notice the strange  syntax of the strings, that's ES6 template literals or "strings on steroids".

Demo

var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
  table += `<tr>`;
  for (var j = 0; j < array[i].length; j++) {
    if (i === 1 && j === 2) {
      table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
    } else {
      table += `<td>${array[i][j]}</td>`;
    }
  }
  table += `</tr>`;
  document.getElementById("Invtable").innerHTML = table;
}

function cvpls() {
  return array = [
    [4, 5, 6, 9, 2],
    ['img', 'img', 'img', 'img', 'img'],
    ['d', 'b', 'g', 'i', 'o']
  ];
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  border: 1px solid black
}</code>```

```

Body:
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "" + "";
                } else if {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

Body:
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:

if (i === 1 && j === 2) {...

If you want the whole 2nd row with the same image in each cell then it should be:

if (i === 1) {...

If you want a entire 3rd column to have the same image then it would be:

if (j === 2) {...

If it's a different image for every cell, then name each file by table coordinates like this...

img1-2.png

...then change the string that renders an image inside a cell as:

 table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`

Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...

 table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`

... and the array would be something like this:

  var array = [
      ['rt','AD','1000.png','uy','ii'],
      ['rt','AD','1001.png','uy','ii'],
      ['rt','AD','1002.png','uy','ii']
    ];

BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.

Also you'll notice the strange  syntax of the strings, that's ES6 template literals or "strings on steroids".

Demo

var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
  table += `<tr>`;
  for (var j = 0; j < array[i].length; j++) {
    if (i === 1 && j === 2) {
      table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
    } else {
      table += `<td>${array[i][j]}</td>`;
    }
  }
  table += `</tr>`;
  document.getElementById("Invtable").innerHTML = table;
}

function cvpls() {
  return array = [
    [4, 5, 6, 9, 2],
    ['img', 'img', 'img', 'img', 'img'],
    ['d', 'b', 'g', 'i', 'o']
  ];
}

td {
  border: 1px solid black
}

<table id='Invtable'></table>


问:
Transition doesn't work on hover off
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

```<code>$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})
</code>```

答:
CSS transition cant be paused or stopped in the middle of a transition. If we reset the transition duration in the middle of a transition it just stop the last transition.

And JQUERY does not support background change with transition effect that much efficient like CSS does. JQUERY transition will be like fadeOut->change background Image->fadeIn. that wont be nice, right?

So alternatively you could queue those mouseover and mouseout events to trigger them one after another.

Note : Obviously it will trigger the mouseover and mouseout events lately (like once we mouseover and immediately mouseout then the mouseout will run only after finishing the mouseover event that is 1 second). But we don't have an alternative.

var animating = false,
  funqueue = [];
$("#flag").hover(function() {
  funqueue.push(function() {
    //console.log("mouseover");
    $("#flag").css({
      'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
      'background-size': 'cover',
      'transition': '1s'
    });
  });
  if (!animating) executeFunctionQueue();
}, function() {
  funqueue.push(function() {
    //console.log("mouseout");
    $("#flag").css({
      'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
      'background-size': 'cover',
      'transition': '1s'
    });
  });
  if (!animating) executeFunctionQueue();
});

function executeFunctionQueue() {
  var funct = funqueue.shift();
  if (funct) {
    animating = true;
    funct.call();
    setTimeout(function() {
      if (funqueue.length == 0) animating = false;
      else
        executeFunctionQueue();
    }, 1000);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag" style="height:300px; background:url('http://visionfi.pl/wp-content/uploads/2017/06/PL.png'); background-size:cover; transition:1s">
</div></code>```

Title: Transition doesn't work on hover off

Body:
i have problem. I wanted to transform div's background when hovering on, it works fine except when i put mouse off the div, the transition doesn't work then. How can i fix this?

When i put mouse off, it instantly changes to original flag.

$("#flag").hover(function(){
 $(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
'background-size':'cover',
'transition':'1 s'
 });
}, function(){
$(this).css({
'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
'background-size':'cover',
'transition':'1 s'
});
})

Body:
CSS transition cant be paused or stopped in the middle of a transition. If we reset the transition duration in the middle of a transition it just stop the last transition.

And JQUERY does not support background change with transition effect that much efficient like CSS does. JQUERY transition will be like fadeOut->change background Image->fadeIn. that wont be nice, right?

So alternatively you could queue those mouseover and mouseout events to trigger them one after another.

Note : Obviously it will trigger the mouseover and mouseout events lately (like once we mouseover and immediately mouseout then the mouseout will run only after finishing the mouseover event that is 1 second). But we don't have an alternative.

var animating = false,
  funqueue = [];
$("#flag").hover(function() {
  funqueue.push(function() {
    //console.log("mouseover");
    $("#flag").css({
      'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/EN.png")',
      'background-size': 'cover',
      'transition': '1s'
    });
  });
  if (!animating) executeFunctionQueue();
}, function() {
  funqueue.push(function() {
    //console.log("mouseout");
    $("#flag").css({
      'background': 'url("http://visionfi.pl/wp-content/uploads/2017/06/PL.png")',
      'background-size': 'cover',
      'transition': '1s'
    });
  });
  if (!animating) executeFunctionQueue();
});

function executeFunctionQueue() {
  var funct = funqueue.shift();
  if (funct) {
    animating = true;
    funct.call();
    setTimeout(function() {
      if (funqueue.length == 0) animating = false;
      else
        executeFunctionQueue();
    }, 1000);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag" style="height:300px; background:url('http://visionfi.pl/wp-content/uploads/2017/06/PL.png'); background-size:cover; transition:1s">
</div>


问:
How to make UIImage round
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

```<code> //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}
</code>```

}

Currently looks like this on a map

答:
You should play around with the cornerRadius property.
It will be something like:

```<code>annotationView.layer.cornerRadius = yourCornerRadius
</code>```

If you set the yourCornerRadius as half of height or width of the annotationView you should get a round annotationView.

If that doesn't works add this line too

```<code>annotationView.layer.maskToBounds = true
</code>```

Title: How to make UIImage round

Body:
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

 //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}

}

Currently looks like this on a map

Body:
You should play around with the cornerRadius property.
It will be something like:

annotationView.layer.cornerRadius = yourCornerRadius

If you set the yourCornerRadius as half of height or width of the annotationView you should get a round annotationView.

If that doesn't works add this line too

annotationView.layer.maskToBounds = true


答:
If you haven't already computed hashes of the files, then you might as well do a proper comparison (instead of looking at hashes), because if the files are the same it's the same amount of work, but if they're different you can stop much earlier.

Of course, comparing a byte at a time is probably a bit wasteful - probably a good idea to read whole blocks at a time and compare them.

Title: Compare files byte by byte or read all bytes?

Body:
I came across this code http://support.microsoft.com/kb/320348 which made me wonder what would be the best way to compare 2 files in order to figure out if they differ.

The main idea is to optimize my program which needs to verify if any file is equal or not to create a list of changed files and/or files to delete / create.

Currently I am comparing the size of the files if they match i will go into a md5 checksum of the 2 files, but after looking at that code linked at the begin of this question it made me wonder if it is really worth to use it over creating a checksum of the 2 files (which is basically after you get all the bytes) ?

Also what other verifications should I make to reduce the work in check each file ?


问:
How can I setup an AWS lambda to access resources in two, separate VPCs?
I'm using Terraform to build an API + corresponding lambda functions.

I have some other infrastructure, which I'd like to think is nicely set up (maybe I'm wrong?):

2 VPCs (let's just call'em test and prod)

Private & public subnets in each VPC

RDS DBs launched in the private subnets

All resources are identical on both VPCs; e.g. there's a test-private-subnet and a prod-private-subnet with exactly the same specs, same for DBs, etc.

Now, I'm working on the API and the lambdas that will power said API.

I don't feel like I need a test & prod API gateway and test & prod lambdas:

lambda code will be the same, just acting on different DB

you can use API stage_variables, with different ips, to achieve a test vs prod environment for the API

But when I try and setup a lambda with the vpc_config block (cause I need it to be associated with the security group that's allowed ingress on the DBs), I get the following error:

```<code>Error applying plan:

1 error(s) occurred:

* module.lambdas.aws_lambda_function.api-lambda-users: 1 error(s) occurred:

* aws_lambda_function.api-lambda-users: Error creating Lambda function: InvalidParameterValueException: Security Groups are required to be in the same VPC.
status code: 400, request id: xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
</code>```

My lambda config looks like this:

```<code>resource "aws_lambda_function" "api-lambda-users" {
  provider = "PROVIDER"
  function_name    = "users"
  s3_key           = "users/${var.lambda-package-name}"
  s3_bucket        = "${var.api-lambdas-bucket}"
  role             = "${aws_iam_role.lambda-role.arn}"
  handler          = "${var.handler-name}"
  runtime          = "${var.lambda-runtime}"

  vpc_config {
    security_group_ids = [
      //"${data.aws_security_group.prod-lambda.id}",
      "${data.aws_security_group.test-lambda.id}"
    ]
    subnet_ids = [
      //"${data.aws_subnet.prod-primary.id}",
      "${data.aws_subnet.test-primary.id}"
    ]
  }
}
</code>```

Notice I'd ideally like to just specify them, together, in their corresponding lists.

Am I missing something?

Suggestions?

Any help, related or not, is much appreciated.

答:
Lambda running inside a vpc is subject to the same networking "rules" as ec2 instances. So it can't "exist" in two VPC's. If the lambda function needs to talk vpc resources in two separate VPC's you could use something like VPC peering or just run two copies of the function in the two different vpc's.

When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have a Network Address Translation (NAT) instance inside the VPC and a VPC Peering connection.

Body:
I'm using Terraform to build an API + corresponding lambda functions.

I have some other infrastructure, which I'd like to think is nicely set up (maybe I'm wrong?):

2 VPCs (let's just call'em test and prod)

Private & public subnets in each VPC

RDS DBs launched in the private subnets

All resources are identical on both VPCs; e.g. there's a test-private-subnet and a prod-private-subnet with exactly the same specs, same for DBs, etc.

Now, I'm working on the API and the lambdas that will power said API.

I don't feel like I need a test & prod API gateway and test & prod lambdas:

lambda code will be the same, just acting on different DB

you can use API stage_variables, with different ips, to achieve a test vs prod environment for the API

But when I try and setup a lambda with the vpc_config block (cause I need it to be associated with the security group that's allowed ingress on the DBs), I get the following error:

Error applying plan:

1 error(s) occurred:

* module.lambdas.aws_lambda_function.api-lambda-users: 1 error(s) occurred:

* aws_lambda_function.api-lambda-users: Error creating Lambda function: InvalidParameterValueException: Security Groups are required to be in the same VPC.
status code: 400, request id: xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx

My lambda config looks like this:

resource "aws_lambda_function" "api-lambda-users" {
  provider = "PROVIDER"
  function_name    = "users"
  s3_key           = "users/${var.lambda-package-name}"
  s3_bucket        = "${var.api-lambdas-bucket}"
  role             = "${aws_iam_role.lambda-role.arn}"
  handler          = "${var.handler-name}"
  runtime          = "${var.lambda-runtime}"

  vpc_config {
    security_group_ids = [
      //"${data.aws_security_group.prod-lambda.id}",
      "${data.aws_security_group.test-lambda.id}"
    ]
    subnet_ids = [
      //"${data.aws_subnet.prod-primary.id}",
      "${data.aws_subnet.test-primary.id}"
    ]
  }
}

Notice I'd ideally like to just specify them, together, in their corresponding lists.

Am I missing something?

Suggestions?

Any help, related or not, is much appreciated.


问:
Can SonarQube analyse T-SQL stored procedures for Microsoft SQL Server?
I got a new task as follows:

Export stored procedures on a daily basis from db

Run them through sonarqube to analyze

I am not a db expert but working in DevOps team. Can anyone tell me if SonarQube supports the analysis of T-SQL stored procedures? If not, which tool does? I see only PL/SQL here in the supported language list: http://docs.sonarqube.org/display/PLUG/Plugin+Library

答:
This one looks promising

https://github.com/gretard/sonar-tsql-plugin

(still in beta version as of now)


问:
How to update a table in another database using triggers?
I want to update another table in another database, this is for stock quantity, when the quantity field get updated then update the other table.

I have this:

```<code>DELIMITER //
DROP TRIGGER IF EXISTS syncFromStockSys //

CREATE TRIGGER syncFromStockSys BEFORE UPDATE on db1.quantity

FOR EACH ROW BEGIN

    UPDATE TABLE db2.oc_product
    SET  `quantity` = NEW.quantity
    WHERE SKU = SKU;   //<<-----------
END //
DELIMITER ;
</code>```

But there is an sintax error
I am using phpMyAdmin to acomplish this.

This is the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'TABLE db2.oc_product
      SET  quantity = NEW.quantity
      WHERE SKU = NEW.' at line 5

答:
Don't use PHP myadmin for any serious work. Get yourself a proper mysql client. As for the error. You shouldn't include the delimiter // inside the trigger block

```<code>DELIMITER //
DROP TRIGGER IF EXISTS syncFromStockSys //

CREATE TRIGGER syncFromStockSys BEFORE UPDATE on db1.quantity

FOR EACH ROW BEGIN

    UPDATE db2.oc_product
    SET  `quantity` = NEW.quantity
    WHERE SKU = SKU;
END //
DELIMITER ;
</code>```

And you probably meant

```<code> WHERE SKU = NEW.SKU;
</code>```

Body:
I want to update another table in another database, this is for stock quantity, when the quantity field get updated then update the other table.

I have this:

DELIMITER //
DROP TRIGGER IF EXISTS syncFromStockSys //

CREATE TRIGGER syncFromStockSys BEFORE UPDATE on db1.quantity

FOR EACH ROW BEGIN

    UPDATE TABLE db2.oc_product
    SET  `quantity` = NEW.quantity
    WHERE SKU = SKU;   //<<-----------
END //
DELIMITER ;

But there is an sintax error
I am using phpMyAdmin to acomplish this.

This is the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'TABLE db2.oc_product
      SET  quantity = NEW.quantity
      WHERE SKU = NEW.' at line 5

Body:
Don't use PHP myadmin for any serious work. Get yourself a proper mysql client. As for the error. You shouldn't include the delimiter // inside the trigger block

DELIMITER //
DROP TRIGGER IF EXISTS syncFromStockSys //

CREATE TRIGGER syncFromStockSys BEFORE UPDATE on db1.quantity

FOR EACH ROW BEGIN

    UPDATE db2.oc_product
    SET  `quantity` = NEW.quantity
    WHERE SKU = SKU;
END //
DELIMITER ;

And you probably meant

 WHERE SKU = NEW.SKU;


问:
Linked List, read from text file, and sort by key
I'm trying to sort the Linked List by the key( priority number, the int number) from highest to lowest, with the data from text file. I'm stucking at insert the item and sort them.
Here is My text file.

Myjob 66

Junk   17

Fun    25

Important   96

Vital       99

MoreFun    28

Work      69

Assignment  44

Here is my Linked List class

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

@SuppressWarnings("unused")
public class LinkedList {
    Node head;
    Node prev;
    Node cur;
    Node node;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

//insert method
public void insert(Data dt){
    try {
        if(head==null){
            head = new Node(dt.getData(), null);
            System.out.println("Opps");
            }
        else if (dt.getData().num > head.dt.num){
            head = new Node(dt.getData(),head);
            System.out.println("Was Here");}
        else if (head.getNext()==null){
            head.setNext(new Node(dt.getData(),null));
            }
        else{
            cur = head.getNext();
            for(prev = head;cur!= null;cur=cur.getNext()){
                if(cur.dt.num>prev.dt.num){
                    Node temp = new Node(dt.getData(),cur);
                    prev.setNext(temp);
                    break;
                }
                else{
                    prev=cur;

                }
            }
        }
    }
        catch (NullPointerException e){
            System.out.println("Here is Error");
        }

}

//Running Linked list
public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        Data dt = new Data();

        l1.insert(dt);

}
</code>```

}

Here is My Node class:

```<code>public class Node {
Data dt;
Node next;

public Node(Data dt, Node next){
    this.dt=dt;
    this.next=next;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt.getData();
}

}
</code>```

Here is my Data class:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {

protected String name;
protected int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

//getter to get Data
@SuppressWarnings("unused")
public Data getData(){
        try{
            int count =0;
            File x = new File("Asg2Data.txt");
            Scanner sc = new Scanner(x);
            while (sc.hasNext()){
                String name = sc.next();
                int num = sc.nextInt();
                Data data= new Data(name,num);
                System.out.println("Name = "+ name+"          "+"Priority = "+num);
                System.out.println(" ");
                count++;
            }
            System.out.println("Total Objects: "+count);
            sc.close();
        }catch(FileNotFoundException e){
            System.out.println("Error");
        }
        return this;
}

//Compare Function
//  public int compare(Data dt){
//      if (this.getData().num > dt.getData().num)
//          return 1;
//      else if (this.getData().num < dt.getData().num)
//          return -1;
//      else
//          return 0;
//  }

// Testing: Worked !!!!!
    public static void main(String[] args){
        Data d1 = new Data();
        d1.getData();
    }

}
</code>```

My currently output, when I run from Linked List class:

```<code>Name = Myjob          Priority = 66

Name = Junk          Priority = 17

Name = Fun          Priority = 25

Name = Important          Priority = 96

Name = Vital          Priority = 99

Name = MoreFun          Priority = 28

Name = Work          Priority = 69

Name = Assignment          Priority = 44

Total Objects: 8
Opps
</code>```

My insert method always stop at the first if statement, and never keep going. I have no clue how to fix it. At the mean time, it can not perform the insert the data + sort them by the priority number from highest to lowest.  Can anyone help me ? I'm super new in Java. Thank you so much.

-Dustin

答:
Your advices are so awesome.  I just fix my code. And it works well now. for now I'm still stucking with the sorting part.  I'm doing insertionSort.  and here is my code.

```<code>public Node insertSort(Node node){
       Node sortedNode = null;
       while(node != null){
        Node current = node;
        node = node.next;
        Node x;
        Node previous = null;
        for(x = sortedNode; x != null; x = x.next){
            if(current.getData().getNum() > x.getData().getNum()){
                    break;
             }
             previous = x;
        }
        if(previous == null){
              current.next = sortedNode;
              sortedNode = current;
        }
        else{
           current.next = previous.next;
           previous.next = current;
        }
      }
      return sortedNode; }
</code>```

My output is

```<code>Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null
</code>```

they skips whatever greater than 66.  Do you have any ideas how to fix this issue, so it can dipslay from 99 down to 17? I rearrange the order in the text file, with the highest first. then It can perform sorting from 99 back to 17 perfectly.  But with the original order, my program just perform sorting from 66 to lowest. I don't know why ,and how to fix it? Thank you so much.

Body:
I'm trying to sort the Linked List by the key( priority number, the int number) from highest to lowest, with the data from text file. I'm stucking at insert the item and sort them.
Here is My text file.

Myjob 66

Junk   17

Fun    25

Important   96

Vital       99

MoreFun    28

Work      69

Assignment  44

Here is my Linked List class

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

@SuppressWarnings("unused")
public class LinkedList {
    Node head;
    Node prev;
    Node cur;
    Node node;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

//insert method
public void insert(Data dt){
    try {
        if(head==null){
            head = new Node(dt.getData(), null);
            System.out.println("Opps");
            }
        else if (dt.getData().num > head.dt.num){
            head = new Node(dt.getData(),head);
            System.out.println("Was Here");}
        else if (head.getNext()==null){
            head.setNext(new Node(dt.getData(),null));
            }
        else{
            cur = head.getNext();
            for(prev = head;cur!= null;cur=cur.getNext()){
                if(cur.dt.num>prev.dt.num){
                    Node temp = new Node(dt.getData(),cur);
                    prev.setNext(temp);
                    break;
                }
                else{
                    prev=cur;

                }
            }
        }
    }
        catch (NullPointerException e){
            System.out.println("Here is Error");
        }

}

//Running Linked list
public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        Data dt = new Data();

        l1.insert(dt);

}

}

Here is My Node class:

public class Node {
Data dt;
Node next;

public Node(Data dt, Node next){
    this.dt=dt;
    this.next=next;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt.getData();
}

}

Here is my Data class:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {

protected String name;
protected int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

//getter to get Data
@SuppressWarnings("unused")
public Data getData(){
        try{
            int count =0;
            File x = new File("Asg2Data.txt");
            Scanner sc = new Scanner(x);
            while (sc.hasNext()){
                String name = sc.next();
                int num = sc.nextInt();
                Data data= new Data(name,num);
                System.out.println("Name = "+ name+"          "+"Priority = "+num);
                System.out.println(" ");
                count++;
            }
            System.out.println("Total Objects: "+count);
            sc.close();
        }catch(FileNotFoundException e){
            System.out.println("Error");
        }
        return this;
}

//Compare Function
//  public int compare(Data dt){
//      if (this.getData().num > dt.getData().num)
//          return 1;
//      else if (this.getData().num < dt.getData().num)
//          return -1;
//      else
//          return 0;
//  }

// Testing: Worked !!!!!
    public static void main(String[] args){
        Data d1 = new Data();
        d1.getData();
    }

}

My currently output, when I run from Linked List class:

Name = Myjob          Priority = 66

Name = Junk          Priority = 17

Name = Fun          Priority = 25

Name = Important          Priority = 96

Name = Vital          Priority = 99

Name = MoreFun          Priority = 28

Name = Work          Priority = 69

Name = Assignment          Priority = 44

Total Objects: 8
Opps

My insert method always stop at the first if statement, and never keep going. I have no clue how to fix it. At the mean time, it can not perform the insert the data + sort them by the priority number from highest to lowest.  Can anyone help me ? I'm super new in Java. Thank you so much.

-Dustin

Body:
Your advices are so awesome.  I just fix my code. And it works well now. for now I'm still stucking with the sorting part.  I'm doing insertionSort.  and here is my code.

public Node insertSort(Node node){
       Node sortedNode = null;
       while(node != null){
        Node current = node;
        node = node.next;
        Node x;
        Node previous = null;
        for(x = sortedNode; x != null; x = x.next){
            if(current.getData().getNum() > x.getData().getNum()){
                    break;
             }
             previous = x;
        }
        if(previous == null){
              current.next = sortedNode;
              sortedNode = current;
        }
        else{
           current.next = previous.next;
           previous.next = current;
        }
      }
      return sortedNode; }

My output is

Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null

they skips whatever greater than 66.  Do you have any ideas how to fix this issue, so it can dipslay from 99 down to 17? I rearrange the order in the text file, with the highest first. then It can perform sorting from 99 back to 17 perfectly.  But with the original order, my program just perform sorting from 66 to lowest. I don't know why ,and how to fix it? Thank you so much.