Q:

Initialize a static const non-integral data member of a class

Consider the sample program below:
#include <iostream>

using namespace std;

class test
{
   public:
      static const float data;
};

float const test::data = 10;   // Line1

int main()
{
   cout << test::data;
   cout << "\n";

   return 0;
}

Please note the comment Line1 in the sample code.
Questions:

Is Line1 doing the initialization of the date member data?
Is Line1 the only way to initialize a static const non-integral data member?

A:

Is Line1 doing the initialization of the date member data?

It certainly is, as well as providing the definition of the object. Note that this can only be done in a single translation unit, so if the class definition is in a header file, then this should be in a source file.

Is Line1 the only way to initialize a static const non-integral data member?

In C++03 it was. In C++11, any static member of const literal type can have an initialiser in the class definition. You still need a definition of the member if it's "odr-used" (roughly speaking, if you do anything that needs its address, not just its value). In this case, the definition again needs to be in a single translation unit, and must not have an initialiser (since there's already one in the class definition).

A:

In contemporary C++ you can initialize any constant expression inline. This requires a change of syntax:
class test
{
   public:
      static constexpr float data = 10.0f;
};

float constexpr test::data;

A:

Line1 does definition of the static data member data, which includes setting its value.
For static data members of non-integral types, member definition is indeed the only place to set a value. For integers, longs, enums, etc. you can put the value in with the declaration. You must still include a definition, but in that case you must not put in any value.

EDIT: As Mike Seymor pointed out, the #2 is out of date. According to the new C++11 standard, the alternative syntax that was reserved only for integral types by the 1998 and C++03 standards has been extended to all constants, regardless of their type.


Q:

Declare javascript function, jQuery

in my main js file where I put all my jQuery stuff I have following new funcitons:
function getDate(){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return  day"."+month+"."+year;
}

function getTime(){
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    if (minutes < 10){
        minutes = "0" + minutes;
    }

    return  hours":"+minutes;
}

...but when I have these functions added to my main js file the jquery part does not work anymore. any ideas?

A:

Well for starters, you were concatenating strings wrongly.
function getDate(){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return day + "." + month + "." + year;
}

function getTime(){
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    if (minutes < 10){
        minutes = "0" + minutes;
    }

    return hours + ":" + minutes;
}


Q:

JavaScript - 'this' inside setTimeout and requestAnimationFrame

My question is related to the following:
setTimeout() inside JavaScript Class using “this”
calling a function inside setTimeout and inside a function
I'm trying to implement a simple animation loop. The draw function is a member function of a state object. I'm having problems getting 'this' to work within the setTimeout and requestAnimationFrame.
I have the following code:
ANIM.State.prototype = {
    constructor: ANIM.State,
    play: function(){
        if(!this.paused){
            var that = this;
            setTimeout(function(){
                requestAnimationFrame(that.play);
                that.setFrameNum(that.currentFrame + 1); //draw code is in here
            }, 1000 / 24);
        }
    }
};

However, when I call play(), it runs twice and stops.
Is there a better way to do this? I'd really like to keep this function as a class function, and not a global one, if possible.

A:

You can solve your issue with .bind() like this:
requestAnimationFrame(that.play.bind(that));

The problem is all that is passed to requestAnimationFrame() is a reference to the .play method and it is then executed as a normal function call so this inside it will be wrong and will not point to your object.  This is a common problem when passing a method as a callback where you want it to be called as obj.method().
There are numerous possible work-arounds, but the easiest in modern browsers is to use .bind() as I've shown above.  This actually creates a small stub function that then calls that.play() rather than just play() so that the object reference is used as you need and it's that stub function that is passed to requestAnimationFrame().
You could also do it like this (creating your own stub function), though .bind() seems cleaner to me:
requestAnimationFrame(function() {
    that.play();
});


Q:

Xcode 9 Visual Memory Debugger broken

With the Xcode 9 GM, I can't seem to get the visual memory debugger to work. Clicking on the memory graph icon just pauses the program, but nothing else happens. Scheme: NSZombie detection is disabled, memory logging is enabled.
What else could be wrong?

A:

Rebooting the computer fixed it. Leaving the Q&A here for everyone with the same problem.


Q:

Apply text color on disabled=true textbox

I would like to know if it's possible to force a CSS Color on a "disabled=true" textbox?
By default, this attribute is removing the css font color and replacing it by a very light gray.
Thanks

A:

input[disabled='disabled'] {
  color:blue;
  }

source


Q:

Yet another Python text editor

Here's what I managed to do. It is rather limited and I had to get help from the internet in some places.
Can you review it, give me some tips on making the code better, cleaner, faster etc.?
editor.py
import tkinter
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox
import os

try:
    import config
    import menu
    import syntaxhl
    import findtool

except ImportError as e:
    import sys
    sys.exit("Import error.\nRaw: {}".format(e))

class Editor(object):

    def editor(self):
        self.root = tkinter.Tk()

        self.config = config.config()
        self.syntaxcolor = config.syntaxHighligh()

        self.root.wm_title(self.config.editor_title)
        self.root.attributes("-alpha", self.config.transparency)

        # Scrollbar
        self.scrollbar = tkinter.Scrollbar(self.root)
        self.scrollbar.pack(side = tkinter.RIGHT, fill = tkinter.Y)

        # Editor.
        self.editor_space = tkinter.Text(self.root)
        self.editor_space.config(undo = self.config.undo, width = self.config.width,
                                 height = self.config.height, fg = self.config.foreground,
                                 bg = self.config.background, insertbackground = self.config.cursorColor,
                                 yscrollcommand = self.scrollbar.set,
                                 font = (self.config.font, self.config.font_size))

        self.editor_space.pack(fill = tkinter.X)
        self.scrollbar.config(command = self.editor_space.yview)

        # Find tool
        find = findtool.Find(self.editor_space)

        # Menu.
        # Note: The order of the instances is the order in witch the menus will appear.
        self.mn = tkinter.Menu(self.root)
        self.filemenu = menu.FileMenu(self.mn, self.openFile,
                                      self.saveFile, self.destroy,
                                      self.root)

        self.toolmenu = menu.ToolsMenu(self.mn, self.clear,
                                       self.syntaxHighlight,
                                       find.find)

        self.prefmenu = menu.Settings(self.mn, self.openConfigFile)
        self.helpmenu = menu.HelpMenu(self.mn, self.about)

        # Close event.
        if self.config.askokcancel:
            self.root.protocol("WM_DELETE_WINDOW", self.destroy)

        self.root.config(menu = self.mn)

        self.root.mainloop()

    def openConfigFile(self):
        try:
            with open("config.py") as file:
                for line in file.readlines():
                    self.editor_space.insert(tkinter.END, line)

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def destroy(self):
        ako = tkinter.messagebox.askokcancel("Quit", "Are you sure you want to exit?")
        if ako:
            self.root.quit()

    def clear(self):
        self.editor_space.delete("1.0", tkinter.END)

    def saveFile(self):
        path = tkinter.filedialog.asksaveasfilename(defaultextension = self.config.defext)
        filename = os.path.basename(path)

        try:
            with open(filename, "w") as wf:
                wf.write(self.editor_space.get("0.0", tkinter.END))

            tkinter.messagebox.showinfo(None, "File saved.")

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def openFile(self):
        self.clear()
        file = tkinter.filedialog.askopenfile()
        try:
            for line in file.readlines():
                self.editor_space.insert(tkinter.END, line)

            self.syntaxHighlight()

        except IOError as e:
            tkinter.messagebox.showerror("Error", "Couldn't open file.")

        except Exception as e:
            tkinter.messagebox.showerror("Error", "Error.\n{}".format(repr(e)))

    def syntaxHighlight(self):
        for keyw, color in getattr(self.syntaxcolor, "colors").items():
            syntaxhl.highlight(self.editor_space, keyw, color)

    def about(self):
        pass

config.py
class config(object):
    editor_title = "TEdit"
    undo = 1 # 1 - Enable

    # The default extension used when saving a file.
    defext = ".txt"

    # Size of the editor window.
    width = 150
    height = 50

    askokcancel = False
    matchColor = "blue"

    # Theme
    transparency = 1
    background = "black"
    foreground = "white"
    font = "Arial"
    font_size = 18
    cursorColor = "green"

class syntaxHighligh(object):
    colors = {"import" : "red",
              "def" : "red",
              "format" : "red",
              "if" : "red",
              "class" : "red",
              "else" : "red",
              "elif" : "red",
              "=" : "red",
              "try" : "red",
              "except" : "red",
              "finally" : "red",
              "yield" : "red",
              "return" : "red",
              "not" : "red",
              "pass" : "red",
              "for": "red",
              "pass": "red",
              "in" : "red",
              "print" : "red",
              "lambda" : "red",
              }

findtool.py
import tkinter
import tkinter.ttk
import config

class Find(object):

    def __init__(self, es):
        self.editor_space = es
        self.config = config.config()

    def find(self):
        # Find window and stuff.
        root = tkinter.Tk()
        tkinter.Label(root, text = "Seach for: ").grid(row = 1, column = 0)

        input_ = tkinter.ttk.Entry(root, width = 20)
        input_.grid(row = 1, column = 1)

        self.editor_space.tag_configure("search", background = self.config.matchColor)

        # Search button.
        tkinter.ttk.Button(root, text = "Search", command=lambda: self.search_editor_space(input_.get())).grid(row = 2, column = 1,
                                                                                columnspan = 2)

        # On close.
        root.protocol("WM_DELETE_WINDOW", lambda: self.destroy_find_window(root))

    def destroy_find_window(self, root):
        self.editor_space.tag_remove("found", "1.0", tkinter.END)
        root.destroy()

    def search_editor_space(self, searchfor):
        # Actual search.
        # Got from(with small modifications): http://www.java2s.com/Code/Python/GUI-Tk/SearchstringinText.html
        # Thanks.

        self.editor_space.tag_config("found", foreground = self.config.matchColor)
        countVar = tkinter.IntVar()

        item = "1.0"

        while True:
            item = self.editor_space.search(searchfor, item, tkinter.END, count = countVar)

            if not item:
                break

            lastindex = "{} + {}c".format(item, countVar.get())

            self.editor_space.tag_add("found", item, lastindex)

            item = lastindex

menu.py
import tkinter
import tkinter.ttk

class FileMenu(object):

    def __init__(self, menubar, openFunc, saveFunc, closeFunc, root):
        self.of = openFunc
        self.sf = saveFunc
        self.cf = closeFunc

        self.menu = tkinter.Menu(menubar)

        filemenu = tkinter.Menu(self.menu)
        filemenu.add_command(label = "Open", command = self.of)
        filemenu.add_command(label = "Save", command = self.sf)
        filemenu.add_separator()
        filemenu.add_command(label = "Exit", command = self.cf)

        menubar.add_cascade(label = "File", menu = filemenu)

class HelpMenu(object):

    def __init__(self, menubar, aboutFunc):
        self.helpmenu = tkinter.Menu(menubar)

        self.helpmenu.add_command(label = "About", command = aboutFunc)

        menubar.add_cascade(label = "Help", menu = self.helpmenu)

class ToolsMenu(object):

    def __init__(self, menubar, clearFunc, syntaxHighL, find):
        self.cf = clearFunc
        self.fd = find
        self.sh = syntaxHighL
        self.toolsmenu = tkinter.Menu(menubar)

        self.toolsmenu.add_command(label = "Clear", command = self.cf)
        self.toolsmenu.add_command(label = "Find", command = self.fd)
        self.toolsmenu.add_command(label = "Syntax highlighting", command = self.sh)

        menubar.add_cascade(label = "Tools", menu = self.toolsmenu)

class Settings(object):

    def __init__(self, menubar, configFile):
        self.prefmenu = tkinter.Menu(menubar)

        self.prefmenu.add_command(label = "Settings", command = configFile)

        menubar.add_cascade(label = "Preferences", menu = self.prefmenu)

syntaxhl.py
import tkinter

def highlight(editor_space, searchfor, color):
    countVar = tkinter.StringVar()

    pos = "1.0"

    while True:
        pos = editor_space.search(searchfor, pos, tkinter.END, count = countVar)

        if not pos:
            break

        lastindex = "{} + {}c".format(pos, countVar.get())

        editor_space.tag_add("keyword", pos, lastindex)

        pos = lastindex

    editor_space.tag_configure("keyword", foreground = color)

main.py
try:
    import editor

except ImportError as e:
    import sys
    sys.exit("editor.py module missing.")

if __name__ == '__main__':
    edit = editor.Editor()
    edit.editor()

A:

As mentioned by @L3viathan, the config class should be a dictionary, not a static class of attributes. When you ever need to store values in such a way, that a grouped together under a category, use a dictionary, like this:
CONFIG = {
    "config-attribute": "config-attribute-value"
    ...
}

Secondly, your naming is off. Functions and variables should be in lower_snake_case, and classes should be in PascalCase. If the variable is constant, it should be in UPPERCASE_SNAKE_CASE.
I'm not sure if you're using Python 3.x, or Python 2.x, but if you're using Python 3.x, you don't need to explicitly inherit all your classes from object. You can just write them like this: class MyClass:. If you're using Python 2.x though, you should continue explicitly inheriting from object.
You're mixing use of single quotes, '', and double quotes, "". Preferably, you should choose one, and stick with that.
You need two blank spaces in between your top level functions/classes. This is part of the official style guide.
Finally, add some comments. Your code is fairly readable, but it could definitely use some comments. First off, add some docstrings, """ ... """, to describe what your functions and classes do. To describe blocks of code, just use online comments, # ....


Q:

How to for loop on pandas dataframe by grouping the values by dates then extracting the filtered group to be saved as a new dataframe

I've been trying to find out how I can efficiently group the rows in my dataframe using a for loop based on the column ' Date (UTC)'. For every similar date, I need to extract all the rows with that date and save it to a new dataframe. Below is the sample of my data.
data = pd.read_csv('MasterData.csv')
print(data)

    Date (UTC)    Magnitude    Vector Station
0   2020-01-05    26.474679 -0.730455   A
1   2020-01-05    30.746291  0.020503   B
2   2020-01-05    37.829401  0.252316   C
3   2020-01-05  1904.611372  0.977388   D
4   2020-01-19    38.441813 -0.044736   B
5   2020-01-19    31.067455  0.419826   C
6   2020-01-19    15.972198 -0.592661   A
7   2020-01-19  1261.038155  0.977394   D
8   2020-02-02    36.628855  0.518991   B
9   2020-02-02    29.724500 -0.818267   A
10  2020-02-02   673.138440  0.977481   D
11  2020-02-02    13.119385  0.327124   C
12  2020-02-16     7.864772  0.311480   C
13  2020-02-16   312.438088  0.977436   D
14  2020-02-16     7.422883 -0.735439   A
15  2020-02-16    30.693853  0.079296   B
16  2020-02-16     4.722992 -0.434787   E
17  2020-03-01    27.501789  0.393106   C
18  2020-03-01   479.118903  0.977505   D
19  2020-03-01    10.022614 -0.887412   A
20  2020-03-01     4.171703 -0.338138   E
21  2020-03-01    26.057769  0.307710   B
22  2020-03-15   580.257861  0.977406   D
23  2020-03-15    17.528845 -0.927358   A
24  2020-03-15     2.963810  0.222188   E
25  2020-03-15    17.535629 -0.052694   B
26  2020-03-15    38.560337  0.283103   C
27  2020-03-29   943.100243  0.977399   D
28  2020-03-29    36.560799 -0.105109   B
29  2020-03-29    17.055374 -0.677127   A
30  2020-03-29     4.614302 -0.315060   E
31  2020-04-12  1095.538437  0.977369   D
32  2020-04-12     6.650060  0.660921   E
33  2020-04-12    55.495947 -0.316548   B
34  2020-04-12    16.269334 -0.614226   A

print(data.dtypes)

 Date (UTC)     object
Magnitude      float64
Vector         float64
Station         object
dtype: object

The expected output is that for every new dataframe saved from the filtered data, I need to plot the magnitude and vector of all the stations in a given date using matplotlib quiver.

A:

It's possible to create an empty dictionary and then group the dates into groups and do a loop process.
df_dict = {}
for name, group in df.groupby('Date_UTC'):
    df_dict[name] = group

df_dict.values()
    dict_values([    Date_UTC    Magnitude Vector Station
0 2020-01-05    26.474679     -0.730455A
1 2020-01-05    30.746291      0.020503B
2 2020-01-05    37.829401      0.252316C
3 2020-01-05  1904.611372      0.977388D,     Date_UTC    Magnitude Vector Station
4 2020-01-19    38.441813     -0.044736B
5 2020-01-19    31.067455      0.419826C
6 2020-01-19    15.972198     -0.592661A
7 2020-01-19  1261.038155      0.977394D,      Date_UTC   Magnitude Vector Station
 ...])

You can also get simply grouping
for name, group in df.groupby('Date_UTC'):
    print('split_date:', name)
    print(group)

    split_date: 2020-01-05 00:00:00
    Date_UTC    Magnitude Vector Station
0 2020-01-05    26.474679     -0.730455A
1 2020-01-05    30.746291      0.020503B
2 2020-01-05    37.829401      0.252316C
3 2020-01-05  1904.611372      0.977388D
split_date: 2020-01-19 00:00:00
    Date_UTC    Magnitude Vector Station
4 2020-01-19    38.441813     -0.044736B
5 2020-01-19    31.067455      0.419826C
6 2020-01-19    15.972198     -0.592661A
7 2020-01-19  1261.038155      0.977394D
....

Create dataframe
df_list = ['df_0','df_1','df_2','df_3','df_4','df_5','df_6','df_7']
i = 0
for name, group in df.groupby('Date_UTC'):
    df_list[i] = group
    i += 1

df_0
    Date_UTC    Magnitude   Vector Station
0   2020-01-05  26.474679   -0.730455A
1   2020-01-05  30.746291   0.020503B
2   2020-01-05  37.829401   0.252316C
3   2020-01-05  1904.611372 0.977388D


Q:

Apache Commons Validator and JUnit

I'm using Apache Commons Validator to validate input within a builder pattern.
Once build() is called on the builder, the variables are checked using methods such as:
Validate.notNull(oranges, "Oranges was not set.");

When testing my code, I can see that when I do not set oranges, I do indeed get the message "Oranges was not set". However, the exception that is thrown is still a NullPointerException.
In my unit tests, I want to check that the validator is used and a message is output, but clearly using:
@Test(expected = NullPointerException.class)

will pass regardless of whether the Validator is used or a message is set.
Is there a way I can check that the validator is used and the message is set in JUnit? If not, is there a library that will allow me to do this?

A:

You should only check the external behaviour of your code. In your case this is: it throws a NullPointerException with the appropriate message.
There are different ways for testing exceptions (see JUnit Wiki). You can always use JUnit's ExpectedException rule
public class YourTest {
  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void test() {
    ...
    thrown.expect(NullPointerException.class);
    thrown.expectMessage("Oranges was not set.");
    builder.build();
  }
}

With Java 8 you can use the method exceptionThrownBy provided by the library Fishbowl. It allows you to use Arrange-Act-Assert pattern.
public class YourTest {
  @Test
  public void test() {
    ...
    Throwable exception = exceptionThrownBy(() -> builder.build());
    assertEquals(NullPointerException.class, exception.getClass());
    assertEquals("Oranges was not set.", exception.getMessage());
  }
}


Q:

Prove by induction: $2!\cdot 4!\cdot 6!\cdot\cdot\cdot (2n)!\ge ((n+1)!)^n$

Prove by induction: $2!\cdot 4!\cdot 6!\cdot\cdot\cdot (2n)!\ge ((n+1)!)^n$
For $n=1$ inequality holds.
$(*)$For $n=k$
$2!\cdot\cdot\cdot (2k)!\ge ((k+1)!)^k$
Multiplying LHS and RHS with $(2k+2)!$ gives
$$2!\cdot\cdot\cdot (2k)!(2k+2)!\ge ((k+1)!)^k(2k+2)!$$
Assume (by contradiction)$$2!\cdot\cdot\cdot (2k)!(2k+2)!< ((k+1)!)^k(2k+2)!$$
$$2!\cdot\cdot\cdot (2k)!(2k+2)!-((k+1)!)^k(2k+2)!<0$$
$$(2k+2)!(2!\cdot\cdot\cdot (2k)!-((k+1)!)^k)<0$$
$(2!\cdot\cdot\cdot (2k)!-((k+1)!)^k)\ge 0$ by $(*)$, thus inequality holds $\forall n\in\mathbb{N}$
Is this proof correct?

A:

First, show that this is true for $n=1$:
$\prod\limits_{k=1}^{1}(2k)!\geq(1+1)!^{1}$
Second, assume that this is true for $n$:
$\prod\limits_{k=1}^{n}(2k)!\geq(n+1)!^{n}$
Third, prove that this is true for $n+1$:
$\prod\limits_{k=1}^{n+1}(2k)!=$
$\color\red{\prod\limits_{k=1}^{n}(2k)!}\cdot(2(n+1))!\geq$
$\color\red{(n+1)!^{n}}\cdot(2(n+1))!=$
$(n+1)!^{n}\cdot(2n+2)!=$
$(n+1)!^{n}\cdot(n+1)!\cdot\dfrac{(2n+2)!}{(n+1)!}=$
$(n+1)!^{n+1}\cdot\dfrac{(2n+2)!}{(n+1)!}=$
$(n+1)!^{n+1}\cdot\underbrace{(n+2)\cdot(n+3)\cdot\ldots\cdot(2n+2)}_{n+1\text{ times}}\geq$
$(n+1)!^{n+1}\cdot\underbrace{(n+2)\cdot(n+2)\cdot\ldots\cdot(n+2)}_{n+1\text{ times}}=$
$(n+1)!^{n+1}\cdot(n+2)^{n+1}=$
$(n+2)!^{n+1}$

Please note that the assumption is used only in the part marked red.


Q:

NGINX basic authentication based on environment variable

I'm setting up a docker image with nginx-lua installed. The scenario is to have a basic authentication on staging, but not in production. My idea was to have an ENV variable with the name of the stage and check the value in the nginx.conf file.
The content of the docker-compose.yml file (for staging, and for production the STAGE env will be prod of course):
docs-router:
  build: ./nginx
  environment:
    - API_BASE_URI=staging.example.com
    - DOCS_STATIC_URI=docs-staging.example.com
    - STAGE=staging
  ports:
    - "8089:8089"
    - "8090:8090"

The content of the nginx.conf file:
...

env API_BASE_URI;
env DOCS_STATIC_URI;
env STAGE;

...

http {
  server {
    listen 8089 default_server;
    charset utf-8;
    resolver 8.8.8.8;
    access_log off;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location ~ ^(/.*\.(?:apib|svg))?$ {
      set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") }
      set_by_lua_block $stage { return os.getenv("STAGE") }
      set $unprotected "prod";

      if ($stage = $unprotected) {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
      }

      proxy_pass https://$api_base_uri$1;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

But it's not working. Any idea, how can I achieve this?

A:

I just find a solution with some help from Serverfault. It's not the best one because the URLs are in the nginx.conf file, but it solves my problem:
I just removed the variable form the docker-compose.yml file:
docs-router:
  build: ./nginx
  environment:
    - API_BASE_URI=staging.example.com
    - DOCS_STATIC_URI=docs-staging.example.com
  ports:
    - "8089:8089"
    - "8090:8090"

And then I mapped the URLs in the nginx.conf file:
...

env API_BASE_URI;
env DOCS_STATIC_URI;

...

http {

  ##
  # URL protection
  ##
  map $http_host $auth_type {
    default "off";
    stage1.example.com "Restricted";
    stage2.example.com "Restricted";
  }

  server {
    listen 8089 default_server;
    charset utf-8;
    resolver 8.8.8.8;
    access_log off;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location ~ ^(/.*\.(?:apib|svg))?$ {
      set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") }

      auth_basic $auth_type;
      auth_basic_user_file /etc/nginx/.htpasswd;

      proxy_pass https://$api_base_uri$1;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

If there is a better / nicer solution for this, please let me know.


Q:

Regex help advanced

I have a regex problem
I need to validate a user given pre defined string to check if there are no mistakes in that string. I made unit test below the tests so you can see what string must match and what don't.
What i already have and works for most:
/^product:\[(.*?)\]|default:\[(.*?)\]$/

What still needs to be tested is there must not be any whitespaces this does not count for the values between the [] And the | must be there. but not at the end
return array(
        array(
            'default:[6_400]',
            TRUE
        ),
        array(
            'default:[bla_bla]',
            TRUE
        ),
        array(
            'default:[bla _ bla]',
            TRUE
        ),
        array(
            'product:8[8_400]|default:[6_400]',
            TRUE
        ),
        array(
            'product:8[8_400]|default:[6_400]|product:10[10_400]',
            TRUE
        ),
        array(
            'product:8[8_400]|product:12 [12_400]|default:[6_400]',
            FALSE
        ),
        array(
            'roduct:8[8_400]|product:12[12_400]|default[6_400',
            FALSE
        ),
        array(
            'default:6_400',
            FALSE
        ),
        array(
            'product:8[8_400]',
            FALSE
        ),
        array(
            'product:8[8_400]default:[6_400]',
            FALSE
        ),
        array(
            'product:8[8_400]|default:[6_400]|',
            FALSE
        ),
    );

A:

Looking at your examples, I think you mean that inside the brackets you want word characters or spaces (you probably don't want #$%^&&, null and other such stuff)...
\[[\w\s]+\]

This apparently can be proceded by either product:number or default:
((product:\d+)|(default:))(\[[\w\s]+\])

Clauses must be separated by | but the matching string must not end with '|'
((product:\d+)|(default:))(\[[\w\s]+\])(\|(?!$)|$)

This can occur one or more times
(((product:\d+)|(default:))(\[[\w\s]+\])(\|(?!$)|$))+

And we must have at least one full, legal default clause:
(?=.*?default:\[[\w\s]+\])(((product:\d+)|(default:))(\[[\w\s]+\])(\|(?!$)|$))+

and fill the whole line:
^(?=.*?default:\[[\w\s]+\])(((product:\d+)|(default:))(\[[\w\s]+\])(\|(?!$)|$))+$

Here it is in action http://regexr.com?3275i
Note that since I have not included any patterns that allow white-space anywhere other than in the brackets, nothing special needs to be done to prohibit it outside of the brackets
Also note that I have created many capturing groups (for simplicity/readability) but you can eliminate them by placing ?: after any ( you don't want to capture. This improves performance somewhat. Besides testing things in regexr.com, this site is often helpful for learning/building regular expressions:
http://www.regular-expressions.info/


Q:

On hook_form_alter setting select list options for a field

By default select options i have left empty in admin of that content type.
I am trying to alter select list option of a content type using hook_form_alter.
I am setting the values to select values and is getting assigned.
Only issue is that its getting logged out with single refresh to create form of that content type form or try to submit that form. What am i doing wrong in the code.
Thanks in advance.
function hook_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'product_node_form')
    {

            $users = db_select('users', 'u');
            $users->join('users_roles','ur','u.uid = ur.uid');
            $users->fields('u',array('name'));
            $users->fields('ur',array('uid'));
            $users->condition('ur.rid',6,'=');
            $users->orderBy('u.uid');
            $users = $users->execute()->fetchAll();

            $vendor_list = array("Tan" => "Tan");

            foreach($users as $key => $user)
            {
                $vendor_list[$user->name] = $user->name;
            }
            $form['field_publish_to']['und']['#options'] = $vendor_list;
    }
}

A:

Try to rename the variable $user/ $users. May be your code is overwriting the default $user object of drupal. Try after renaming the variables $user/ $users.


Q:

Git Hub - 2 users / same machine

I've followed various posts and am getting very frustrated with this.
I want to have 2 git hub accounts on my machine, but when I push to my repository, my first account is always used.
Here is what I've done:
Created a new ssh key and added to git hub.
Created a config file:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
Host github-panthro
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_panthro

Then:
git init
git add *
git commit -m "first commit"
git remote add origin git@github-panthro:panthro/myrepo.git
git push origin master

But it keeps pushing up changes by my original git hub user. Where am I going wrong?

A:

Commits you pushnto github will appear authored by the user whose email matches the email you set with
git config --global user.email

But you can also config a local email on a per-repo basis if you omit the --global parameter. As you see, this email is linked to your working copy, so you can't have two emails here. What you can do, instead, is to have two working copies in your local machine, each one with its corresponding user email. Obviously you need to make sure they keep in sync somehow.
In second place, if you are using the same local user to push to github, and both working copies are using the ssh remote address, then you are using the same key to push, even if your commits do appear aliased by the two emails you previously set.
If you want to use different accounts for real, then you can either use the https remote address (which will make you authenticate before pushing) or you must set two users in your machine, each one with his own ssh key, and don't push with user A in the repo that has user's B email.
Edit: I just tried in one of my projects and it works (github didn't recognize my bogus email, so it displayed the user.name instead)


Q:

Python Group by more than one keys in List of Dictionary

I have the list of dictionary like:
[ {'price': 100,  'product_id': 30089, 'grade_id': 24, 'qty': 1.0},
  {'price': 200, 'product_id': 30089, 'grade_id': 22, 'qty': 1.0},
   {'price': 100,  'product_id': 30089, 'grade_id': 24, 'qty': 5.0},
   {'price': 300, 'product_id': 30993, 'grade_id': 22, 'qty': 1.0} ]

Now I want to make group by this List by 2 keys (product_id and grade_id) and the final result will be a new list like:
[ {'price': 200,  'product_id': 30089, 'grade_id': 24, 'qty': 6.0},
  {'price': 200, 'product_id': 30089, 'grade_id': 22, 'qty': 1.0},
  {'price': 300, 'product_id': 30993, 'grade_id': 22, 'qty': 1.0}]

A:

l=[ {'price': 100,  'product_id': 30089, 'grade_id': 24, 'qty': 1.0},
   ...:   {'price': 200, 'product_id': 30089, 'grade_id': 22, 'qty': 1.0},
   ...:    {'price': 100,  'product_id': 30089, 'grade_id': 24, 'qty': 5.0},
   ...:    {'price': 300, 'product_id': 30993, 'grade_id': 22, 'qty': 1.0} ]

d={}

for x in l:
   ...:     p_id = x['product_id']
   ...:     g_id = x['grade_id']
   ...:     key = str(p_id) + '_' + str(g_id)
   ...:     if not key in d:
   ...:         d[key] = {'price': x['price'] , 'product_id': p_id , 'grade_id': g_id, 'qty': x['qty']}
   ...:     else:
   ...:         d[key]['price'] += x['price']
   ...:         d[key]['qty'] += x['qty']

l1 = [d[x] for x in d]

l1

[{'grade_id': 22, 'price': 200, 'product_id': 30089, 'qty': 1.0},
 {'grade_id': 22, 'price': 300, 'product_id': 30993, 'qty': 1.0},
 {'grade_id': 24, 'price': 200, 'product_id': 30089, 'qty': 6.0}]


Q:

convert String to Clob and vice versa in Hibernate

Suppose that I have a Class:
class EventTransaction {
    .....
    private Clob dataXML;

    public Clob getDataXML() {
       return dataXML;
    }

    public void setDataXML(Clob dataXML) {
       this.dataXML = dataXML;
    }
}

And Hibernate mapping xml:
 <property name="dataXML" type="java.sql.Clob">
        <column name="XML" sql-type="CLOB"/>
 </property>

In java code, how to I convert a String to Clob and vice versa to save into to the database:
Ex: EventTransaction et = new EventTransaction();
    String xml = "fdfsafafafa";
    et.setDataXML(convertStringToClob(xml));
    HibernateTemplate.saveOrUpdate(et);

Could you please help how to implement function convertStringToClob(String data);
Thanks,

A:

Do this
@Column(name='xml')
@Lob
private String dataXML;

public String getDataXML() {
   return dataXML;
}

public void setDataXML(String dataXML) {
   this.dataXML = dataXML;
}

So there is no need to convert, and everything is done by Hibernate.
I showed it using annotations, the same thing can be done using .hbm.xml files.

A:

Here is code I made a long time ago to convert a Clob to a String. It's meant to be used in a utility class.
    public static String convertClobToString(Clob clob) throws IOException, SQLException {
            Reader reader = clob.getCharacterStream();
            int c = -1;
            StringBuilder sb = new StringBuilder();
            while((c = reader.read()) != -1) {
                 sb.append(((char)c));
            }

            return sb.toString();
     }

And if I am not mistaken, to create a Clob you would do something like this
     Clob myClobFile = new SerialClob("my string".toCharArray());


Q:

Preserve key:value values in text while regex replacing non-word characters in keys (Notepad++)

Trying without luck in Notepad++ to replace any non-word characters \W with underscore _ from a block of multi-line text, with exception to (and right of) a colon : (which doesn't occur on every line- something of space-delineated hierarchy, terminating in a key-value pair). A python solution could be of use as well, as I'm trying to do other things with it once reformatted. Example:
This 100% isn't what I want
  Yet, it's-what-I've got currently: D@rnit :(
This_100_is_what_I_d_like: See?
  Indentation_isn_t_necessary
    _to_maintain_but_would_be_nice: :)<-preserved!
  I_m_Mr_Conformist_over_here: |Whereas, I'm like whatever's clever.|
If_you_can_help: Thanks 100.1%!

A:

I admit that I'm answering an off-topic question I just liked the problem. Hold CTRL+H,  enable Regular Expressions in N++ then search for:
(:[^\r\n]*|^\s+)|\W(?<![\r\n])

And replace with:
(?1\1:_)

Regex has two main parts. First side of outer alternation which matches leading spaces of a line (indentation) or every thing after first occurrence of a colon, and second side which matches a non-word character except a carriage return \r or newline \n character (in negative lookbehind) to preserve linebreaks. Replacement string is a conditional block which says if first capturing group is matched replace it with itself and if not replace it with a _.


Q:

Put across vs get across

I'd like to ask if these two words are interchangeable ?
put something ↔ across phrasal verb
1   to explain your ideas, beliefs etc in a way that people can understand:
2  put yourself across  British English to explain your ideas and opinions clearly so that people understand them and realize what sort of person you are:

He was trying to put across a serious point.
Sue's never been very good at putting herself across at interviews.
Television can be a useful way of putting across health messages

get something ↔ across
to succeed in communicating an idea or piece of information to someone, or to be communicated successfully

It took him ages to get his point across.
We must get across the simple fact that drugs are dangerous.
I was trying to get across how much I admired them.
It is important that we get this message across to voters.
What message are you trying to get across to the consumer?

Source : Longman and McMillan Dictionary

A:

As @FumbleFingers has pointed out

to put across an idea (AmE)
to put forward an idea (BrE)

is to suggest or present an idea.
Also a standard BrE phrase is

I put it to you that...

which also has the meaning "here's an example", "take for example"

to get across an idea (AmE, BrE)
to make them understand, to get them to understand

is to have the suggested idea understood.

We weren't able to get across that going out in a storm was a bad idea.
  In our pitch, we got across to the Board that increase advertising will increase sales.

A related phrase get through can have the same meaning as get across

What we are trying to get through to you is that this is very important.
What we are trying to get across is that this is very important
"You might understand if I could ever get through that thick skull of yours." he said in exasperation.


Q:

Unordered Map with Multiple Value and it's lookup

I am working on an assignment where I have been given a large tab separated value txt file and I have to search through it using a good data structure. Now the problem I am facing is that I don't know if I am inserting the values correctly in this unordered_map with the key being a string and the values being a vector of struct.
Secondly if I want to search how will it do it? For example if i enter the first ID how can i print out or access the other elements present in the struct?
Below is the sample data & code
id    effectiveTime    active    moduleId    definitionStatusId
100005    20020131    0    900000000000207008    900000000000074008
101009    20020131    1    900000000000207008    900000000000074008
102002    20020131    1    900000000000207008    900000000000074008
103007    20020131    1    900000000000207008    900000000000074008
104001    20020131    1    900000000000207008    900000000000073002
105000    20040731    0    900000000000207008    900000000000074008
106004    20020131    1    900000000000207008    900000000000074008
107008    20020131    1    900000000000207008    900000000000074008
108003    20020131    1    900000000000207008    900000000000074008
109006    20020131    1    900000000000207008    900000000000074008
110001    20020131    1    900000000000207008    900000000000074008
111002    20020131    1    900000000000207008    900000000000074008
112009    20020131    1    900000000000207008    900000000000074008
113004    20020131    1    900000000000207008    900000000000074008
114005    20020131    1    900000000000207008    900000000000074008
115006    20020131    1    900000000000207008    900000000000074008
116007    20020131    1    900000000000207008    900000000000074008
117003    20020131    1    900000000000207008    900000000000074008
118008    20020131    1    900000000000207008    900000000000074008
119000    20020731    1    900000000000207008    900000000000073002
120006    20020131    1    900000000000207008    900000000000074008
121005    20020131    1    900000000000207008    900000000000074008

And here is the code
#include <iostream>
#include <vector>
#include <fstream>
#include <unordered_map>

using namespace std;

struct concept
{
    string id,effectiveTime,active,moduleId,definitionStatusId;
};

int main ()
{
    unordered_map<string,vector<concept>> concepts;
    ifstream conceptStream("concept.txt");
    if (!conceptStream.is_open())
    {
        cout << "Failed to open\n";
        return 0;
    }
    string id,effectiveTime,active,moduleId,definitionStatusId;
    string conceptLine;
    getline(conceptStream, conceptLine);
    while (!conceptStream.eof())
    {
        getline(conceptStream, id, '\t');
        getline(conceptStream, effectiveTime, '\t');
        getline(conceptStream, active, '\t');
        getline(conceptStream, moduleId, '\t');
        getline(conceptStream, definitionStatusId, '\n');
        concepts[id] = {{id,effectiveTime,active,moduleId,definitionStatusId}};
    }

  return 0;
}

A:

You search for a value by using find. You have a value if the iterator returned isn't equal to end().
unordered_map<string,vector<concept>>::const_iterator it = concepts.find(id);
if (it != concepts.end()) {} //You have a value

The vector you have inserted will always have one entry, so you could do away with that, but as you have it you need to get the first element of the vector.
if (it != concepts.end())
  cout << it->second[0].id << it->second[0].effectiveTime; //etc

Of course maybe you intend to see if the ID already exists and add it to the vector if it does. That will work, but maybe you should consider std::unordered_multimap as Shawn suggested, and if not, change the key type to concept as there will only ever be one element in the vector.
If you do remove the vector the access code becomes simpler:
if (it != concepts.end())
  cout << it->second.id << it->second.effectiveTime; //etc


Q:

How to add multiple views inside SwipeRefreshLayout, with one of them being recyclerview?

I have a recyclerview inside SwipeRefreshLayout. and at the end of recyclerview, I'd like to add a button, but I'm unable to do so. Here the code :
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/refresh"
    android:layout_width="wrap_content"
    android:layout_below="@+id/toolbar"
    android:paddingBottom="50dp"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/load_more"
        android:layout_alignParentBottom="true"
        android:textColor="@color/md_black_1000"
        android:text="TEST"/>

</android.support.v4.widget.SwipeRefreshLayout>

The button does not appear at the end of the recyclerview.

A:

SwipeRefreshLayout could have only one child.

Add RecyclerView and Button to vertical LinearLayout and put it into SwipeRefreshLayout.
<android.support.v4.widget.SwipeRefreshLayout>
    <LinearLayout>
        <android.support.v7.widget.RecyclerView>
        <Button>
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

To add Button as last item in RecyclerView you need edit adapter:
1) increase number of rows
@Override
public int getItemCount() {
    return pictureArrayList.size() + 1;
}

2) show Button when list ends
@Override
public void onBindViewHolder(final ExampleHolder holder, final int position) {
    final Picture picture = pictureArrayList.get(position);
    if (position <= pictureArrayList.size()) {
        holder.title.setVisibility(View.VISIBLE);
        holder.button.setVisibility(View.GONE);
        holder.title.setText(picture.getName());
        holder.imageView.setImageResource(picture.getImage());
    } else {
        holder.title.setVisibility(View.GONE);
        holder.button.setVisibility(View.VISIBLE);
    }
}


Q:

webpack extract text plugin prints a lot

I am using the webpack extract text plugin to extract styles into a css file. It prints a lot of stuff like this:

Child extract-text-webpack-plugin:
          + 2 hidden modules
Child extract-text-webpack-plugin:
          + 7 hidden modules
Child extract-text-webpack-plugin:
          + 7 hidden modules
Child extract-text-webpack-plugin:
          + 2 hidden modules
Child extract-text-webpack-plugin:
          + 2 hidden modules
Child extract-text-webpack-plugin:
          + 4 hidden modules

Is there any way to surpress it via config? It's pretty useless and cramps the terminal window.

A:

Yes, it is possible to suppress messages from child plugins by adding { stats: { children: false } } option to your webpack config.
module.exports = {
  stats: {
    children: false
  }
};

There is an issue reported upstream regarding chatty behavior.


Q:

UI grid unable to get selected rows in case of 2 grids(same grid repeated twice)

I have created two ui grids on the same html(both are same).
    I'm trying to get selected row on click of submit button. I'm able to get selected row for second grid but not able to get it for the first grid.
I'm getting selected rows like this:
 onRegisterApi: function(gridApi) {
    $scope.gridApi = gridApi;
    $scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
    }

Plunker: http://plnkr.co/edit/SgYh9QzjCQDOKMMXATlF?p=info
Is there any way to get selected row of both the grids?
Thanks in advance.

A:

That is because the API registers when the grid loads in the DOM. Since you have two grids with the same scope, when the second loads, it's API becomes what is defined by $scope.gridApi. Therefore anything you do with that API is interacting with the second grid instance.
The solution here would be to separate the grids out, maybe $scope.gridOptions1, $scope.gridOptions2. For anything that must occur on both, you can call each API independently within the function.
This is what I would do:
http://plnkr.co/edit/nLLR63L4H4NqLoZsGpkS?p=preview
For your submit function, assuming you want a single array with the results, I've updated the function such that it provides one result:
  $scope.submitData = function() {

    var selectedRows1 = $scope.gridApi1.selection.getSelectedRows(),
        selectedRows2 = $scope.gridApi2.selection.getSelectedRows(),
        selectedRows = selectedRows1.concat(selectedRows2);

    console.warn(selectedRows);
    alert(selectedRows.length)
    if (selectedRows.length === 0)
      alert('Please select an item from grid');
    else
      alert(JSON.stringify(selectedRows));

  }


Q:

Related Product gets not added to cart

I have a strange problem on my test system. I'm quite new to magento and think this problem might exist, because it is a test system.
I have some products with related products. If I try to add a product to the shopping cart with it's related product(s). The related product(s) do not get added to the cart.
My first guess was a broken javascript but everything seems to be ok there. My next step was to get myself temper data for firefox. I have verified, that the PostData contains:
product         = $id_of_product
related_product = $id_of_related_product
qty             = $qty_of_product

Still the related product does not get added to the cart. Could this be a problem with the setup of the test system? Changing the quantities works fine for the normal product. Changing the id of the related_product to the id of another product does not add anything to the cart, too.
Thanks in advance
EDIT
Ok, as others might have the same problem I leave the original question and describe here how to debug this.
The first thing to do is to deactivate all modules in local and community. The easiest way is to temporarily rename the folders app/code/local and app/code/community and test if it works afterwards. If it does not work you have to search further.
If the error still persists check the post message sent to the server. An easy way to do this is to get the Tamper Data addon for firefox. If the post message does not look like the message in the picture:

The error is probably inside the JavaScript of your app/design/frontend/base/default/template/catalog/product/list/related.phtml file. Change the path to the theme you are using.
The POSTDATA field should contain related_product=Comma_Separated_Ids_Of_Selected_Related_Products
If everything looks good so far, the mistake is somewhere in the code of magento. How magento adds products to the cart is described in a blog post here: http://www.ecomdev.org/2012/12/12/magento-checkout-shopping-cart-flow.html
The POSTDATA is computed in app/code/core/Magento/Checkout/controllers/CartController.php at the lines below
        193  $cart->addProduct($product, $params);
        194  if (!empty($related)) {
        195      $cart->addProductsByIds(explode(',', $related));
        196  }

Make sure the $related variable contains the ids of your related products.
If this is the case this will lead you to app/code/core/Mage/Checkout/Model/Cart.php where in my case the error was.

A:

Ok, I finally can add the related_product to the cart. In the code/core/Mage/Checkout/Model/Cart.php file are two functions for adding products into the cart. The first is called public function addProduct($productInfo, $requestInfo=null), the second function is public function addProductsByIds($productIds).
The related_product is added by id, the others are added with the addProduct() function. The adding by id does not seem to work (at least for me it did not. Although magento used the unaltered Cart.php file from 1.7.0.2.
I solved this by altering the Cart.php file like this:
 /**
 * Add product to shopping cart (quote)

 * This is the original function pasted from
 * Mage/Checkout/Model/Cart.php line 245
 * The function is working and adding products to the cart

 *
 * @param   int|Mage_Catalog_Model_Product $productInfo
 * @param   mixed $requestInfo
 * @return  Mage_Checkout_Model_Cart
 */
public function addProduct($productInfo, $requestInfo=null)
{
    $product = $this->_getProduct($productInfo);
    $request = $this->_getProductRequest($requestInfo);

    $productId = $product->getId();

    if ($product->getStockItem()) {
        $minimumQty = $product->getStockItem()->getMinSaleQty();
        //If product was not found in cart and there is set minimal qty for it
        if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty
            && !$this->getQuote()->hasProductId($productId)
        ){
            $request->setQty($minimumQty);
        }
    }

    if ($productId) {
        try {
            $result = $this->getQuote()->addProduct($product, $request);
        } catch (Mage_Core_Exception $e) {
            $this->getCheckoutSession()->setUseNotice(false);
            $result = $e->getMessage();
        }
        /**
         * String we can get if prepare process has error
         */
        if (is_string($result)) {
            $redirectUrl = ($product->hasOptionsValidationFail())
                ? $product->getUrlModel()->getUrl(
                    $product,
                    array('_query' => array('startcustomization' => 1))
                )
                : $product->getProductUrl();
            $this->getCheckoutSession()->setRedirectUrl($redirectUrl);
            if ($this->getCheckoutSession()->getUseNotice() === null) {
                $this->getCheckoutSession()->setUseNotice(true);
            }
            Mage::throwException($result);
        }
    } else {
        Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));
    }

    Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
    $this->getCheckoutSession()->setLastAddedProductId($productId);
    return $this;
}

/**
 * Adding products to cart by ids

 * This function is the altered function, which works for me
 * the edited lines are marked.

 *
 * @param   array $productIds
 * @return  Mage_Checkout_Model_Cart
 */
public function addProductsByIds($productIds)
{
    $allAvailable = true;
    $allAdded     = true;

    if (!empty($productIds)) {
        foreach ($productIds as $productId) {
            $productId = (int) $productId;
            if (!$productId) {
                continue;
            }
            $product = $this->_getProduct($productId);
            if ($product->getId() && $product->isVisibleInCatalog()) {
                try {
                    $this->getQuote()->addProduct($product);
                } catch (Exception $e){
                    $allAdded = false;
                }

                /**
                 * START EDIT
                 */

                /**
                * String we can get if prepare process has error
                */
                if (is_string($result)) {
                    $redirectUrl = ($product->hasOptionsValidationFail())
                        ? $product->getUrlModel()->getUrl(
                            $product,
                            array('_query' =>array                                   ('startcustomization' => 1))
                            )
                        : $product->getProductUrl();
                    $this->getCheckoutSession()->setRedirectUrl($redirectUrl);
                    if ($this->getCheckoutSession()->getUseNotice() === null) {
                        $this->getCheckoutSession()->setUseNotice(true);
                    }
                    Mage::throwException($result);
                }
                Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
                $this->getCheckoutSession()->setLastAddedProductId($productId);

                /**
                 * STOP EDIT
                 */

            } else {
                $allAvailable = false;
            }
        }

        if (!$allAvailable) {
            $this->getCheckoutSession()->addError(
                Mage::helper('checkout')->__('Some of the requested products are unavailable.')
            );
        }
        if (!$allAdded) {
            $this->getCheckoutSession()->addError(
                Mage::helper('checkout')->__('Some of the requested products are not available in the desired quantity.')
            );
        }
    }
    return $this;
}

So i copied the lines from the other function. Does anyone think this will have some drawbacks? For me it looks like this introduces another check if everything works correct by examining the return string. But i don't know if dispatching the event might have some negative effects. As i stated, I'm new to magento and would like to know if this is solid solution.
Does anyone know, why the functions are different? Because they do basically the same. The only difference is, that the second function can add more than product. Maybe in this case dispatching the event is slow?


Q:

c# Get value (text) of a bound textbox in a gridview

I have bound textboxes in a gridview. Code to create the gridview cell:
<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="txtWLA" runat="server" Text='<%# Eval("WLA") %>' />
  </ItemTemplate>
</asp:TemplateField>

I'm trying to loop through my gridview and get the values in the textboxes. I've tried several variations of this:
 txtValue =  row.Cells[1].FindControl("txtWLA").Text;   //I've tried "text" and "textbox" too

But no matter what I try, I keep getting an error telling me that the 'text' value is wrong. Here's the error:
'System.Web.UI.Control' does not contain a definition for 'Text' and no
extension method 'Text' accepting a first argument of type
'System.Web.UI.Control' could be found

I'm baffled. Every resource I try tells me that .Text is the right way to get the contents of a textbox. Can anyone tell me what I'm doing wrong? Thanks.

A:

The return type of FindControl() is System.Web.UI.Control and it does not have a property with the name Text
If you know what the actual type is, just cast and access it:
txtValue =  (row.Cells[1].FindControl("txtWLA") as TextBox).Text;


Q:

Primer on TensorFlow and Keras: The past (TF1) the present (TF2)

The aim of this question is to ask for a bare-minimal guide to get someone up to speed with TensorFlow 1 and TensorFlow 2. I feel like there isn't a coherent guide that explains differences between TF1 and TF2 and TF has been through major revisions and evolving at a rapid pace.
For reference when I say,

v1 or TF1 - I refer to TF 1.15.0
v2 or TF2 - I refer to TF 2.0.0

The questions I have are,

How does TF1/TF2 work? What are their key differences?
What are different datatypes/ data structures in TF1 and TF2?
What is Keras and how does that fit in all these? What kind of different APIs Keras provide to implement deep learning models? Can you provide examples of each?
What are the most recurring warnings/errors I have to look out for while using TF and Keras?
Performance differences between TF1 and TF2

A:

How does TF1/TF2 work? And their differences
TF1
TF1 follows an execution style known as define-then-run. This is opposed to define-by-run which is for example Python execution style. But what does that mean? Define then run means that, just because you called/defined something it's not executed. You have to explicitly execute what you defined.
TF has this concept of a Graph. First you define all the computations you need (e.g. all the layer computations of a neural network, loss computation and an optimizer that minimizes the loss - these are represented as ops or operations). After you define the computation/data-flow graph you execute bits and pieces of this using a Session. Let's see a simple example in action.
# Graph generation
tf_a = tf.placeholder(dtype=tf.float32)
tf_b = tf.placeholder(dtype=tf.float32)
tf_c = tf.add(tf_a, tf.math.multiply(tf_b, 2.0))

# Execution
with tf.Session() as sess:
    c = sess.run(tf_c, feed_dict={tf_a: 5.0, tf_b: 2.0})
    print(c)

The computational graph (also known as data flow graph) will look like below.
     tf_a      tf_b   tf.constant(2.0)
       \         \   /
        \      tf.math.multiply
         \     /
         tf.add
            |
          tf_c

Analogy: Think about you making a cake. You download the recipe from the internet. Then you start following the steps to actually make the cake. The recipe is the Graph and the process of making the cake is what the Session does (i.e. execution of the graph).
TF2
TF2 follows immediate execution style or define-by-run. You call/define something, it is executed. Let's see an example.
a = tf.constant(5.0)
b = tf.constant(3.0)
c = tf_a + (tf_b * 2.0)
print(c.numpy())

Woah! It looks so clean compared to the TF1 example. Everything looks so Pythonic.
Analogy: Now think that you are in a hands-on cake workshop. You are making cake as the instructor explains. And the instructor explains what the result of each step is immediately. So, unlike in the previous example you don't have to wait till you bake the cake to see if you got it right (which is a reference to the fact that you cannot debug code). But you get instant feedback on how you are doing (you know what this means).
Does that mean TF2 doesn't build a graph? Panic attack
Well yes and no. There's two features in TF2 you should know about eager execution and AutoGraph functions.

Tip: To be exact TF1 also had eager execution (off by default) and can be enabled using tf.enable_eager_execution(). TF2 has eager_execution on by default.

Eager execution
Eager execution can immediately execute Tensors and Operations. This is what you observed in the TF2 example. But the flipside is that it does not build a graph. So for example you use eager execution to implement and run a neural network, it will be very slow (as neural networks do very repetitive tasks (forward computation - loss computation - backward pass) over and over again).
AutoGraph
This is where the AutoGraph feature comes to the rescue. AutoGraph is one of my favorite features in TF2. What this does is that if you are doing "TensorFlow" stuff in a function, it analyses the function and builds the graph for you (mind blown). So for example you do the following. TensorFlow builds the graph.
@tf.function
def do_silly_computation(x, y):
    a = tf.constant(x)
    b = tf.constant(y)
    c = tf_a + (tf_b * 2.0)
    return c

print(do_silly_computation(5.0, 3.0).numpy())

So all you need to do is define a function which takes the necessary inputs and return the correct output. Most importantly add @tf.function decorator as that's the trigger for TensorFlow AutoGraph to analyse a given function.

Warning: AutoGraph is not a silver bullet and not to be used naively. There are various limitations of AutoGraph too.

Differences between TF1 and TF2

TF1 requires a tf.Session() object to execute the graph and TF2 doesn't
In TF1 the unreferenced variables were not collected by the Python GC, but in TF2 they are
TF1 does not promote code modularity as you need the full graph defined before starting the computations. However, with the AutoGraph function code modularity is encouraged

What are different datatypes in TF1 and TF2?
You've already seen lot of the main data types. But you might have questions about what they do and how they behave. Well this section is all about that.
TF1 Data types / Data structures

tf.placeholder: This is how you provide inputs to the computational graph. As the name suggest, it does not have a value attached to it. Rather, you feed a value at runtime. tf_a and tf_b are examples of these. Think of this as an empty box. You fill that with water/sand/fluffy teddy bears depending on the need.
tf.Variable: This is what you use to define the parameters of your neural network. Unlike placeholders, variables are initialized with some value. But their value can also be changed over time. This is what happens to the parameters of a neural network during back propagation.
tf.Operation: Operations are various transformations you can execute on Placeholders, Tensors and Variables. For example tf.add() and tf.mul() are operations. These operations return a Tensor (most of the time). If you want proof of an op that doesn't return a Tensor, check this out.
tf.Tensor: This is similar to a variable in the sense that it has an initial value. However, once they are defined, their value cannot be changed (i.e. they are immutable). For example, tf_c in the previous example is a tf.Tensor.

TF2 Data types / Data structures

tf.Variable
tf.Tensor
tf.Operation

In terms of the behavior nothing much has changed in data types going from TF1 to TF2. The only main difference is that, the tf.placeholders are gone. You can also have a look at the full list of data types.
What is Keras and how does that fit in all these?
Keras used to be a separate library providing high-level implementations of components (e.g. layers and models) that are mainly used for deep learning models. But since later versions of TensorFlow, Keras got integrated into TensorFlow.
So as I explained, Keras hides lot of unnecessary intricacies you have to deal with if you were to work with bare-bone TensorFlow. There are two main things Keras offers Layer objects and Model objects for implementing NNs. Keras also has two most common model APIs that lets you develop models: the Sequential API and the Functional API. Let's see how different Keras and TensorFlow are in a quick example. Let's build a simple CNN.

Tip: Keras allows you to achieve what you can with do achieve with TF much easier. But Keras also provide capabilities that are not yet strong in TF (e.g. text processing capabilities).

height=64
width = 64
n_channels = 3
n_outputs = 10

Keras (Sequential API) example
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(2,2),
activation='relu',input_shape=(height, width, n_channels)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=(2,2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(n_outputs, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.summary()

Pros

Straight-forward to implement simple models

Cons

Cannot be used to implement complex models (e.g. models with multiple inputs)

Keras (Functional API) example
inp = Input(shape=(height, width, n_channels))
out = Conv2D(filters=32, kernel_size=(2,2), activation='relu',input_shape=(height, width, n_channels))(inp)
out = MaxPooling2D(pool_size=(2,2))(out)
out = Conv2D(filters=64, kernel_size=(2,2), activation='relu')(out)
out = MaxPooling2D(pool_size=(2,2))(out)
out = Flatten()(out)
out = Dense(n_outputs, activation='softmax')(out)
model = Model(inputs=inp, outputs=out)
model.compile(loss='binary_crossentropy', optimizer='adam')
model.summary()

Pros

Can be used to implement complex models involving multiple inputs and outputs

Cons

Needs to have a very good understanding of the shapes of the inputs outputs and what's expected as an input by each layer

TF1 example
# Input
tf_in = tf.placeholder(shape=[None, height, width, n_channels], dtype=tf.float32)

# 1st conv and max pool
conv1 = tf.Variable(tf.initializers.glorot_uniform()([2,2,3,32]))
tf_out = tf.nn.conv2d(tf_in, filters=conv1, strides=[1,1,1,1], padding='SAME') # 64,64
tf_out = tf.nn.max_pool2d(tf_out, ksize=[2,2], strides=[1,2,2,1], padding='SAME') # 32,32

# 2nd conv and max pool
conv2 = tf.Variable(tf.initializers.glorot_uniform()([2,2,32,64]))
tf_out = tf.nn.conv2d(tf_out, filters=conv2, strides=[1,1,1,1], padding='SAME') # 32, 32
tf_out = tf.nn.max_pool2d(tf_out, ksize=[2,2], strides=[1,2,2,1], padding='SAME') # 16, 16
tf_out = tf.reshape(tf_out, [-1, 16*16*64])

# Dense layer
dense = conv1 = tf.Variable(tf.initializers.glorot_uniform()([16*16*64, n_outputs]))
tf_out = tf.matmul(tf_out, dense)

Pros

Is very good for cutting edge research involving atypical operations (e.g. changing the sizes of layers dynamically)

Cons

Poor readability

Caveats and Gotchas
Here I will be listing down few things you have to watch out for when using TF (coming from my experience).
TF1 - Forgetting to feed all the dependent placeholders to compute the result
tf_a = tf.placeholder(dtype=tf.float32)
tf_b = tf.placeholder(dtype=tf.float32)
tf_c = tf.add(tf_a, tf.math.multiply(tf_b, 2.0))

with tf.Session() as sess:
    c = sess.run(tf_c, feed_dict={tf_a: 5.0})
    print(c)

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_8' with dtype float
       [[node Placeholder_8 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]

The reason you get an error here is because, you haven't fed a value to tf_b. So make sure you feed values to all the dependent placeholder to compute a result.
TF1 - Be very very careful of data types
tf_a = tf.placeholder(dtype=tf.int32)
tf_b = tf.placeholder(dtype=tf.float32)
tf_c = tf.add(tf_a, tf.math.multiply(tf_b, 2.0))

with tf.Session() as sess:
    c = sess.run(tf_c, feed_dict={tf_a: 5, tf_b: 2.0})
    print(c)

TypeError: Input 'y' of 'Add' Op has type float32 that does not match type int32 of argument 'x'.

Can you spot the error? It is because you have to match data types when passing them to operations. Otherwise, use tf.cast() operation to cast your data type to a compatible data type.
Keras - Understand what input shape each layer expects
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(2,2),
activation='relu',input_shape=(height, width)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=(2,2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(n_outputs, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam')

ValueError: Input 0 of layer conv2d_8 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 64, 64]

Here, you have defined an input shape [None, height, width] (when you add the batch dimension). But Conv2D expects a 4D input [None, height, width, n_channels]. Therefore you get the error above. Some commonly misunderstood/error-prone layers are,

Conv2D layer - Expects a 4D input [None, height, width, n_channels]. To know about the convolution layer/operation in more detail have a look at this answer
LSTM layer - Expects a 3D input [None, timesteps, n_dim]
ConvLSTM2D layer - Expects a 5D input [None, timesteps, height, width, n_channels]
Concatenate layer - Except the axis the data concatenated on all other dimension needs to be the same

Keras - Feeding in the wrong input/output shape during fit()
height=64
width = 64
n_channels = 3
n_outputs = 10

Xtrain = np.random.normal(size=(500, height, width, 1))
Ytrain = np.random.choice([0,1], size=(500, n_outputs))

# Build the model

# fit network
model.fit(Xtrain, Ytrain, epochs=10, batch_size=32, verbose=0)

ValueError: Error when checking input: expected conv2d_9_input to have shape (64, 64, 3) but got array with shape (64, 64, 1)

You should know this one. We are feeding an input of shape [batch size, height, width, 1] when we should be feeding a [batch size, height, width, 3] input.
Performance differences between TF1 and TF2
This has already been in discussion here. So I will not reiterate what's in there.
Things I wish I could have talked about but couldn't
I'm leaving this with some links to further reading.

tf.data.Dataset
tf.RaggedTensor


Q:

The role of the extraction matrix in a Kalman filter

The extraction matrix shown as $H_k$ below, transforms the state vector into a form that can be subtracted from the measurements vector:
$\hat{X}_k = \hat{X}_k^- + K_k ({z}_k - H_k \hat{X}_k^-)$
Where $\hat{X}_k^-$ is the projected state (from the state transition model), ${z}_k$ is the measurement vector, and $K_k$ is the Kalman gain.
Why is the filter normally formed in this way? Right now $\hat{X}_k^-$ is being transformed to the "measurement space" (for lack of a better term) and subtracted from the measurement vector, then it is transformed back into the "state space" by being multiplied by $K_k$. Why don't we just transform the measurement matrix instead so that we'd deal with only one transformation?
Is there any benefit in doing it this way?
Thanks!
EDIT: let me explain this better.
I'm proposing to modify the measurement update process so it would be of this form: $\hat{X}_k = \hat{X}_k^- + L_k(G_kz_k - \hat{X}_k^-)$. I feel this would be less computationally taxing. The end result would be the same. Instead of multiplying $\hat{X}_k^-$ by $H_k$ I am multiplying $z_k$ by $G_k$. $L_k$ would be the Kalman gain after it has been modified to be compatible with these changes.

A:

I finally figured this out. The use of the extraction matrix in the conventional way allows for multi-sensor fusion, i.e. more than one sensor measuring each state variable.
For example if $z_1$ and $z_2$ are two measurements for the state variables one can form a measurement vector:
$Z = \begin{bmatrix} z_1 \\ z_2 \end{bmatrix} $
And the state variable is:
$ X = \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix} $
The extraction matrix would be such that $X$ would be converted into a vector that can be subtracted from $Z$:
$H = \begin{bmatrix} h_{11} & h_{12} & h_{13} \\ h_{21} & h_{22} & h_{23} \end{bmatrix} $
In this situation, the Kalman gain would provide an optimal solution based on both measurements. What I was proposing in the original question would cause problems here.


Q:

NullReferenceException was Unhandled (for a class)

I've been trying to fix this class null problem for little bit. I don't understand it. It say that my class is null for some reason. Which then make my LoadContent null too. The additional information says: Object reference not set to an instance of an object.
CharacterInfo Chara;//Chara Class is Null
Chara.LoadContent(Content);// Error pointing to

//This is behind Chara.LoadContent(Content);
texture = Content.Load<Texture2D>("Art/BlueAnvil");
HealthBar = Content.Load<Texture2D>("Art/HealthBar");

Started happening after I add the LoadContent constructor, to the class, and started to using Chara.LoadContent(Content);
Please help me expand my knowledge in C# so I can remember how to fix this.

A:

You need to instantiate your object:
CharacterInfo Chara = new CharacterInfo();

At this point, you're only declaring the variable, but you're not assigning an actual value to it, hence the exception.
If LoadContent is a static factory method  that creates CharacterInfo objects based on the value of the passed parameter, it should be:
CharacterInfo Chara = CharacterInfo.loadContent(Content);


Q:

Enhanced loop for primitives

Is there any short enhanced form of for loop which we can use for primitives.
I have do the legacy code for looping on to primitives, like this
for(int i=0; i<10; i++){
}

Although for objects, we have ehanced for loop like
for(MyObject m : myObjectList){
}

Is there any similar option for primitives also?

A:

Found the solution, IntStreams in java 8 can replace the regular for-loop utilizing IntStream.range()
IntStream.range(1, 4)
.forEach(System.out::println);


Q:

Generating a slug after Active Record object creation in rails

I'm trying to generate a unique slug for an object after the object is created using the after_commit callback.
after_commit :create_slug, on: :create

def create_slug
    self.slug = generate_slug
    self.save
end

When I try to save the object I get a "stack level too deep" error.  I'm assuming because I'm saving the object and it's called the after_commit callback again and again.
What's the best way to generate and save the unique slug in this situation?

A:

I recommend using the after_validation callback on create rather than the after_commit.  You will be calling multiple transactions, which is not the intention of this callback.  What I would do is this:
after_validation(on: :create) do
  self.slug = generate_slug
end

Also make sure there are no save actions going on inside the generate_slug.  That method should simply be returning a value to insert into the slug attribute.


Q:

Why T sql Char() function returns values diffrent from whats specified on asciitable.com

All,I am trying to create a T sql scalar function that removes any extended  ascii characters in a passed in string value.I am doing this using the PatIndex() function as below.One thing I noticed is that the T sql Char() and ascii() functions return a different character/decimal value when invoked with the correct inputs from whats mentioned  in the asciitable.com .Any idea why this is diffrent? The collation used on the database(Sql server 2012) is SQL_Latin1_General_CP1_CI_AS
I use this url for copying and pasting extended ascii characters http://www.rapidtables.com/code/text/ascii-table.htm
SELECT
  ASCII('Ñ') AS tsql_decimal_value,
  165 AS value_from_ascii_table

SELECT
  CHAR(165) AS tsql_value,
  'Ñ' AS value_from_asciitable

My Tsql Function
CREATE FUNCTION dbo.udf_Remove_NON_ASCII_characters (@value AS nvarchar(2000))
RETURNS varchar(2000)
AS
BEGIN

  DECLARE @incorrectcharLoc smallint --Position of bad character
  DECLARE @pattern varchar(140)  --Bad characters to look for

  SELECT
    @pattern = '%[' + CHAR(128) + .... + CHAR(255) + ']%'

  SELECT
    @incorrectcharLoc = PATINDEX(@pattern, @value)

  WHILE @incorrectcharLoc > 0
  BEGIN
    SELECT
      @value = STUFF(@value, @IncorrectcharLoc, 1, '')
    SELECT
      @IncorrectcharLoc = PATINDEX(@Pattern, @value)
  END
  RETURN @value
END

Please see attched screenshot for sql server result sets
Any help would be really appreciated

A:

Having reached my own computer, I first checked the documentation on CHAR() and ASCII().

CHAR() returns an INT ASCII character code
ASCII() returns the ASCII code value of the leftmost character of a character expression

With these presuppositions and for kicks using the letter ñ, I ran the following statement:
SELECT  UPPER('ñ') AS Character         -- returns Ñ
      , ASCII( UPPER('ñ') ) ASCII_Value -- returns 209
      , CHAR( ASCII( UPPER('ñ') ) )     -- returns Ñ
      , CHAR(165) AS CHAR_VALUE2        -- returns ¥

Notice that the ASCII code for the value Ñ is 209, and not 165. Also note that there are disparate unofficial versions that list the ASCII codes, such as ASCII-code.com, which does not list Ñ in the first 200 INT values. The trouble is unofficial sources.
Therefore, we can conclude:

A) Online sources should always be taken with some measure of skepticism, particularly if they are not officially sanctioned documentation (I noticed on my computer that the original source was just a picture, rather than a table)
B) The ASCII table does not have Ñ in the first 200 INT values.

One solution could be to build out your own mapping of the ASCII tables and reference that. Whatever you choose, SQL Server uses the implementation of the ISO ASCII standard, so you might as well make SQL the SOT for these issues.


Q:

Convert Base64 into PDF without converting it into an Image in JAVA

I've done converting PNG to PDF using itext.
How can i convert BASE64 into a PDF File, how can i achieve this.
//b64Image contains base64code from html2canvas, this code is for converting
 base64 to png
String b64Image=request.getParameter("img_val");

b64Image = b64Image.replace("data:image/png;base64,", "");
b64Image = b64Image.replace(" ", "+");

byte[] imageByte;
String path = "C:\\Users\\P.Balraj\\Desktop\\Screenshot.png";
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(b64Image);
File outputfile = new File(path);
    BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(outputfile));
stream.write(imageByte, 0, imageByte.length);
stream.flush();
stream.close();

Thank you

A:

You can add b64 image to pdf like this:
import java.io.FileOutputStream;

//com.lowagie...   old version
//com.itextpdf...  recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
import org.apache.commons.codec.binary.Base64;

public class Image64ToPDF {
    public static void main(String ... args) {
        Document document = new Document();
        //
        String b64Image = "iVBORw0KGgoAAAANSUhEUgAAAJcAAACXCAMAAAAvQTlLAAABF1BMVEX////qQzU0qFNChfT7vAU8gvTz9/5pm/bh6f3m7f4edvMhePPqPi/7tgD7uAD7ugAyfvPpOCjpNCIopUv0+vb62NYAnjf97ezU6tnrTkKv2LhCrF7whX4YokLpLRnC4cn+9/bymZPoHgDt8v4zqkHo9Ov0qqX2vrrpOzb8wgB1vob+7s+ExZNUsmv/+e9XkPXT4PzsX1WZzqX4ycbudW374+JiuHdKqU7btQPsuxaTtfj8w0U8lrSux/prrEQDpljF1vsmf+Gmz8SRsD40pGf/4Kj86cGmsjY3oH85maKAqfc/jtQ/k8Q5nZL3qBT81oTtXC/xfCb1lxvvbyHNtyb8y2MAaPK1syznAhj2nzjuZirzjSD80nX4U1R1AAAFc0lEQVR4nO2YC1faSBiGQwCtEAzJxBgICSGFoMilQERbWy+tdXfb3bXdrXvt//8dO1wOEDIZkkmGePbMo+eoR8DHb9755hs4jsFgMBgMBoPBYDAYDMYzxDo+HzsN1x1C3FqjPT62rNSdjpza0LRNU5aEGZJs2rbkNtpHKUqN3UoGCmV8CLKcqTSOrDSsxg3BRjmt3Oyhc75rq/ZQkIOdlmoZd5dmljO0MZVaR7LdnSVtPJRDWs3MBNfahdWRG7ZWSzPJoa/lCFI0qykm7ZidD83oVtOS2W2aWuMKQbHmyDV6Wk7UZK1juseUtGrbOxYOqWLRsLJcsmitvDJUwu8SR2uOUKHRYC033iLCalGJV8xsUaoW14idLSrVam+rliBJ8hQJjoe7q9aRjZWSzQqcn502BM7Tw4y5uUMoVcsa4sY/W2qMz63Vo+G079rm+jOEDJ1RB5N5OVND/k3HXZlRqhY3Dsy8YNeCWqXVrph0q3VcCSwWfnpxMhLFanFOwCoK9rZp7xyWjFa1uOOAvSgPQ5x2DZtWtbga+lg0h6H+oEPr0nH2+wlSi+KUF4rH3L8IMdNNWatfyp3+mtk0k3Zz88LweJiDYl+8YoJJK8xh6V+JOcjpV4+YlOJ7NXMeZlpQ7LeTlZncSFuL+36YW4it1lLIpG3F9RflmoqJ/yzEZKo31FA8lHIrTucNQ0i7RXBry7gI2bRh2OO0rTjuSsx5xMQvJ0IlbSl4BuV8fP0r/XQtu8R6yf7GTRF7kSD2+njo8xK/Yx5/MNiPArHYo9/r8CPOq5CPQOElqdeTfx1LfaxXNgLFV4Ra/dcIL9wTonmV35F6IeJ1laDXG1Kvks/rEBf7iF75Twl64WIf1Wuf0OvM71VK0muQoNcD8/pfeD2HfKH24+Pz9BKfnoPXoe8cEnMJepH2r/4V1XObuN8j54mzxLyIz0fk/IUL/o7mCeS8+qRgvP4oFosF+DH/LEx/mn9XKPu9iOcv7sGvJV5rmCe8COLgjV+MfF71BV/8dmGMiF7qE6Jg5BcPr5eY+5PneYPolYo+qzz5vcMbMDF3fTP1IinYK/+OIN+O3o4vXs60eL7Xiv5CiHiRb0eOs1YLKX6bWxEV7GCA6BMvyL2WCymKH/glauSCvUOknvR0nLF4h0J8fX2z8gITTA9D4k99rHhxix0pXvIeQMSVRKQrWyDuqjMeSnANf7jxevFqPcpr3CK08gPyLjEDtocPm1qwYriuv0k2n/gywuRfXvi1YMVCi+3tI7Sy2XjLCFvYBcIKoofdlPuIVSSfCVdUDbRYuIztIbXipn6KoqO9eNDd/uSXA6QW8Wi/Th0EiBn6lpAp7++QWtnybQJe3CRIDIARrsNqHfUeKZZIueC/HeQFzdRRQP6V+kQFPGi+Lfu3YzHO0bhGUPRni8l3EBugNZoY8/+m+ZOvYmXii9AmXYwYDwxjUtVaremSKkqrpdW7QF2VuHl/t1GxAfEAvYmiBy/lQk3vTTqQSU83DO+Dwf1nz7lduE1KC65LULPwCECQv2i+XTuKYp9AHjQ1hFggzR+X6Y99YG8Q2MVCAfTP8/jnY9yCAsRiVQyAn8vJdVQP1VgV45u/5PM0tOJWDIbsrhjjDoRB29IutmAY8acINC0d12C3APgoQ240FGznx2v1ot6iIlEN6J3brFTs6JEASuDYg8HoRbpBkVHnIy4mMLqUizVHqfIRagbAhOCdFjJaVRCymQG1Q28bIlDqvaDxYb1UemdntVqijXQVkzSgGp3qTnLlQ9FGPZ03NusGABwNe516OlILWvVqd6IbqqoakOkXfdId1XcaqiAUONdrWh2iaS34Q9o+DAaDwWAwGAwGg8FgMJD8B0Y0n3erXn7HAAAAAElFTkSuQmCC"; // .gif and .jpg are ok too!
        String output = "c:/output.pdf";
        try {
            PdfWriter.getInstance(document, new FileOutputStream(output));
            document.open();
            byte[] decoded = Base64.decodeBase64(b64Image.getBytes());
            document.add(Image.getInstance(decoded));
            document.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Q:

amqp.node library, viewing error

I'm trying to use amqp.node library to connect to rabbit through SSL and according to the doc: http://www.squaremobius.net/amqp.node/ssl.html
you should pass console.warn to the then callback.  In the project I just started work on (my first node project), we are using winston logger.  So how do I actually see the
error because when I do,
var opts = { }; // my ssl info
amqplib.connect("ampws://{user}:{pass}@{host}:{port}", opts).then(function(err, conn) {
    if (err) {
        winstonLogger.error("err: " + err) // this just prints [object Object]
    }
}).then(null, console.warn);

I'm not sure how to map the console.warn to my actual logger.

A:

Try this:
amqplib.connect("ampws://{user}:{pass}@{host}:{port}", opts)
.then( ( conn ) => {
    // use the connection
})
.then( ( null, err ) => {
    winstonLogger.error("err: " + err.stack||err.message||err );
});


Q:

how to do another show action in a show.html.erb in a 2 nested model in rails

I have 2 models - Task and Project.
Now I have already nested my task under projects and I can create a new task inside the views/project/show.html.erb.
Now what I want to do is to do another show action inside of it

      <% @tasks.each do |task| %>

          <%= task.name %>
          <%= task.description %>
           <%= link_to 'Show', project_task_path(@task,:project_id) %>

      <% end %>

  class TasksController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy]
  before_action :set_project
  # GET /tasks
  # GET /tasks.json
  def index
    @tasks = Task.all
  end

  # GET /tasks/1
  # GET /tasks/1.json
  def show
     @tasks = Task.where(project_id: @project.id)
  end

  # GET /tasks/new
  def new
    @task = Task.new
  end

  # GET /tasks/1/edit
  def edit
  end

  # POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(task_params)
    @task.project_id = @project.id

    respond_to do |format|
      if @task.save
        format.html { redirect_to @project, notice: 'Task was successfully created.' }
        format.json { render :show, status: :created, location: @task }
      else
        format.html { render :new }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tasks/1
  # PATCH/PUT /tasks/1.json
  def update
    respond_to do |format|
      if @task.update(task_params)
        format.html { redirect_to @task, notice: 'Task was successfully updated.' }
        format.json { render :show, status: :ok, location: @task }
      else
        format.html { render :edit }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.json
  def destroy
    @task.destroy
    respond_to do |format|
      format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

    def set_project
      @project = Project.find(params[:project_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_params
      params.require(:task).permit(:name, :description)
    end
end

A:

You'll be best looking at partials:

Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

In your case, you'll be able to populate a partial with the relevant tasks for your project:
#app/views/projects/show.html.erb

   <%= render @project.tasks %>

#app/views/projects/_task.html.erb

   <%= task.name %>
   <%= task.decription %>
   <%= link_to 'Show', project_task_path(task,@project) %>

From what I understand, this should answer your question...?


Q:

$A_\epsilon=[0,1]\bigcap\bigcup_{j=1}^\infty N_{1/2^j}(q_j)$. Show that $\partial A_\epsilon =[0,1]\setminus A_\epsilon$.

Let $\{q_k\}$ be an enumeration of the rational numbers in $[0,1]$, and, for $0 < \epsilon<\frac{1}{2}$, let
  $$A_\epsilon=[0,1]\bigcap\bigcup_{j=1}^\infty \left(q_j-\frac{\epsilon}{2^j}, q_j+\frac{\epsilon}{2^j}\right).$$
  Show that $\partial A_\epsilon =[0,1]\setminus A_\epsilon$.

It looks to me that $A_\epsilon=[0,1]$. If we take the infinite union, $\bigcup_{j=1}^\infty \left(q_j-\frac{\epsilon}{2^j}, q_j+\frac{\epsilon}{2^j}\right)$, will we not get $[0,1]$?
How can I proceed?

A:

Let $x \notin A_\varepsilon$ and $r > 0$. Clearly $x \in B(x,r)$. On the other hand, we have that $$B(x, r)\cap \mathbb{Q} = \Big([0,1] \cap \langle x - r, x + r\rangle\Big) \cap \mathbb{Q} \ne \emptyset $$
because $\mathbb{Q}$ is dense in $\mathbb{R}$. In particular $B(x, r) \cap A_\varepsilon \ne \emptyset$ since $\mathbb{Q} \cap [0,1] \subseteq A_\varepsilon$.
Therefore $x \in \partial A_\varepsilon$ since an arbitrary ball around $x$ intersects both $A_\varepsilon$ and $A_\varepsilon^c$.
Now take $x \in A_\varepsilon$. Therefore, there exists $j \in \mathbb{N}$ such that $x \in \left\langle q_j - \frac{\varepsilon}{2^j}, q_j + \frac{\varepsilon}{2^j}\right\rangle \cap [0,1]$ which is an open set in $[0,1]$ so there exists $r > 0$ such that $B(x,r) \subseteq \left\langle q_j - \frac{\varepsilon}{2^j}, q_j + \frac{\varepsilon}{2^j}\right\rangle \cap [0,1]$. Therefore $B(x,r)$ does not intersect $A_\varepsilon^c$ so $x \notin \partial A_\varepsilon$.
We conclude $\partial A_\varepsilon = A_\varepsilon^c = [0,1] \setminus A_\varepsilon$.

Indeed $A_\varepsilon \ne [0,1]$ for $\varepsilon < \frac12$ because if $\lambda$ denotes the Lebesgue measure, we have: $$\lambda\left(A_\varepsilon\right) \le \lambda\left(\bigcup_{j\in\mathbb{N}} \left\langle q_j - \frac{\varepsilon}{2^j}, q_j + \frac{\varepsilon}{2^j}\right\rangle\right) \le \sum_{j=1}^\infty \lambda\left(\left\langle q_j - \frac{\varepsilon}{2^j}, q_j + \frac{\varepsilon}{2^j}\right\rangle\right) = \sum_{j=1}^\infty \frac{\varepsilon}{2^{j-1}} = 2\varepsilon < 1$$
and $\lambda([0,1]) = 1$.


Q:

why notation pat ... means zero or more expressions in scheme macro pattern

When I'm reading the macro part of The Scheme Programming Language, it mentions that when you are trying to define a syntax extension using define-syntax, you should use pat ... to specify zero or more expression in the pattern. Why don't just use ... for zero or more expression, in which case pat ... means one or more expressions?
Also, when the author gives definition of and as follows:
(define-syntax and
  (syntax-rules ()
    [(_) #t]
    [(_ e) e]
    [(_ e1 e2 e3 ...)
     (if e1 (and e2 e3 ...) #f)]))

Why don't just write it like this:
(define-syntax and
  (syntax-rules ()
    [(_) #t]
    [(_ e) e]
    [(_ e1 e2 ...)
     (if e1 (and e2 ...) #f)]))

I have tested this definition with some cases, and I didn't find any problem with it.

A:

Per R6RS, ... must always follow some identifier to get its "zero or more" meaning (it behaves like the Kleene star), so ... and pat ... mean different things: the former is just a literal ... symbol as far as syntax-rules is concerned.
In your example, both forms seem to be the same, but that's because the pattern (_ e1 e2 ...) only fires when there are two or more conjuncts (arguments to and) anyway, since the second pattern (_ e) already handles the case where there's only one conjunct. It doesn't always work this way, and Dybvig apparently found it cleaner to write an explicit "two or more" clause rather than "exactly one" and "one or more" clauses.


Q:

How to add unit tests in Eclipse for a managed ARM C project?

I've got a managed Eclipse project that uses the GNU ARM Embedded Toolchain to compile for an ST microcontroller. What I want to do now is, unit test the code in that project. The framework I want to use for unit testing is Google Test.
I tried creating a second Eclipse project for the unit tests, that uses the standard GNU toolchain. Like this:
Project1 (ARM)
|---src
Project2 (Desktop)
|---test
The problem with that is twofold:

The second project doesn't have access to the source code of the first project (obviously). Therefore I tried creating a static library from the first project for testing purposes, which leads to the second problem.
The Library created from the first project isn't compatible with the second project, because it uses the GNU ARM embedded toolchain instead of the standard GNU toolchain.

To solve the second problem I added a build configuration to the first project to try and compile it with the right toolchain. That didn't work out though.
Another path I went was to have the unit tests in the same project as the actual code and use a build configuration to create an executable for unit testing. Something like this:
Project
|---src
|---test
That didn't work out as well and it kind of seems like it's the same problem as with the first approach anyway.
The problem isn't unit testing in itself. I know how to use Google Test for testing regular C projects in eclipse.
How is unit testing an embedded project usually approached with managed projects in eclipse? Is it possible at all? If so, is it a good way to do it or should I write my own makefile to accompilsh this task?

A:

To do that using eclipse auto generated makefiles, you have to create a Build Configuration for each build (one for target and one for the desktop), accordingly:

Project1, will have to be built as a static library for both platforms. It will contain your application in a platform independent manner.
Project2 will have to be build only for Desktop, it will have tests and tests main, also will link to Project1 library.
A Project3 (with main and platform dependent code) will have to be created and build a an elf or bin, linking to Project1 library for target platform.

It can get more complicated if you decide to run tests on target platform as well;
I have two examples/templates where you can get based, but they are not related to eclipse:

Build with Makefiles with msp430 toolchain, CppUTest as test framework.
https://github.com/felipe-lavratti/UnitTestingEmbeddedC-Demo1
Build using Scons, tests are run in both platforms, dependencies and CppUTest as unit testing framework.
https://github.com/felipe-lavratti/UnitTestYoutubeVideos


Q:

MVC TempData doesn't save in async method

can't figure it out:
Have this.(I've deleted most code to simplify reading)
  [HttpPost]
    public  ActionResult Upload(HttpPostedFileBase file)
    {

        Change();

        return RedirectToAction("Index");
    }

public ActionResult Index()
    {

        return View();
    }
 private async void Change()
    {
        await Task.Run(() =>
            {
                try
                {
                    TempData["Text"] = "Text 1";

                }
                catch
                {
                    TempData["Text"] = "Text 2";
                }

            });

View
@TempData["Text"]
I need to change it, but it doesn't change. Need some help or maybe other ways to do it(I just need to change text depending on conditions in "Change" func and show it to the user).
Thanks!

A:

async void means that the method is fire-and-forget. The controller will not wait for it to finish so by the time you try to set TempData, the response has already been sent back to the client.
Assuming you are using ASP.NET MVC 4 or later, you will have to change the signature of Change to async Task and make your action asynchronous:
[HttpPost]
public  async Task<ActionResult> UploadAsync(HttpPostedFileBase file)
{

    await Change();

    return RedirectToAction("Index");
}

private async Task Change()
{
    await Task.Run(() =>
        {
            try
            {
                TempData["Text"] = "Text 1";

            }
            catch
            {
                TempData["Text"] = "Text 2";
            }
        });
}

Actually, there is no reason to use async/await in Change if it simply calls Task.Run. You can write:
private Task Change()
{
    return Task.Run(() =>
        {
            try
            {
                TempData["Text"] = "Text 1";

            }
            catch
            {
                TempData["Text"] = "Text 2";
            }

        });
}

You can find a full tutorial on using asynchronous methods here


Q:

Is it possible in Gridview to show different images representing different database values?

I have an fieldname called has_Amenities. This fieldname can take one, two, three, four, or five  values at same time.
The values are water, electricity, pets, Full hookup, All

If has_Amenities = "electricity", then show electricity icon but also show blank icons for pets, full hookup and water tap.
If has_Amenities  = "pets", show pets icon as well as blank icons for electricity, full hookup and water
If has_Amenities = "water", show water icon and also show blank icons for pets, full hookup and electricity.
If has_Amenities = "full", show full hookup icon and also show blank icons for pets, water and electricity.
If has_Amenities = "All", then it means it has electricity, water, full hookup and pets. Show all four icons.

We are using gridview and gridview control id is gridview1.
The code below works by displaying just one value - Electricity.
 <asp:TemplateField HeaderText="Facility Has">
   <ItemTemplate>
     <asp:Image ID="ImageDetailItem" width="22" height="22" ImageUrl='<%# IIF(CONVERT.ToString(Eval("has_Amenities")) = "Electricity", "~/images/icon_amps_50.gif", Eval("location","~/images/icon_waterfront_no.gif")) %>' runat="server" />
   </ItemTemplate>
 </asp:TemplateField>

This is not the correct solution.
How do I use all the IF conditions mentioned above and how do I show all four icons in one cell?
Below is an image of how they are laid out.

A:

I did similar things in asp.net webforms using c# like this (i hope VB is not much different)
 <asp:TemplateField>
               <ItemTemplate>
                   <asp:Image runat="server" ImageUrl="<%# ProtectedIsVisible(Item.HasAmenties,"Electricity")? "~/electricity.gif":"~/blank.gif" %>"/>
                   <asp:Image ID="Image1" runat="server" ImageUrl="<%# ProtectedIsVisible(Item.HasAmenties,"Pets")? "~/pets.gif":"~/blank.gif" %>"/>
                   <asp:Image ID="Image2" runat="server" ImageUrl="<%# ProtectedIsVisible(Item.HasAmenties,"Water")? "~/water.gif":"~/blank.gif" %>"/>
               </ItemTemplate>
           </asp:TemplateField>

The page class had protected method,containing all logic
protected bool ProtectedIsVisible(string[] values,string tag)

And I used ItemType property of GridView, set to strongly typed model class,something like
class Model{ public string[] HasAmenties {get;set; }
<asp:GridView ItemType="MyApplication.Model" runat="server" ID="MyGridView">


Q:

Is it possible to power a microcontroller via inductance from an AC power line?

I have an AC mains wire powering a pump running at 220V at 5-10A. Is it possible to wind a secondary wire around the outside of the insulation of one of the two "hot" wires (single-phase) to get low-voltage AC that could be rectified to DC and used to power a microcontroller?
The goal is to monitor current while the pump is in use, using a separate split-core transformer as an analog input, and report usage via Wifi or Zigbee without requiring a separate DC power supply.

A:

No, the wire will not radiate a magnetic field along the lengt of the wire but straight out of the wire. To make a transformer and extract energy you need an magnetic field that alternates. As you will have a split core to measure the current the best idea would be to use it to both measure the current and extract power to your circuit. This only works with a real current transformer and not with a modern Hall effect variant, if you need the Hall effect model for accuracy in your measurements you will need a separate split core current transformer to power your circuit.
The resultant circuit is much like an transformer with only one turn of primary winding, the current in the secondary winding will be the current in the AC wire divided by the number of turns in the current transformers winding. Note that the circuit outputs a current and if the load is not sufficient the voltage can be quite high, therefor you need to be sure to load the current transformer and to have a over voltage protection that can handle the excess power, especially in events of high current on the AC line, like starting currents of an electrical motor.
If you then put a resistor or other current sensing element in series of the output of your current transformer that measures the total current you can know the current trough the AC line at the same time as you uses it to power your current sensing circuit.