Q:

How to fix dates to be similar format?

I am receiving 2 date formats:
1/22/2020

1/22/20

I need to convert 1/22/2020 to 1/22/20
I currently use the following but I am not sure how to do a check and convert it before to add my dates
    foreach($header as $field){
        if (preg_match("/([1-9]|1[0-2])\/([1-9]|[1-2][0-9]|3[0-1])\/[0-9]{2}$/",$field)) {

            if($insert){
                $days[] = ["date" => $field, $type => $value[$field]];
            }
            else{
                $date_index = array_search($field, array_column($globalData[$index]['data'], 'date'));

                $globalData[$index]['data'][$date_index][$type] = $value[$field];
            }
        }
    }

A:

You can use php DateTime::createFromFormat function for converting the date in more robust way.
// filter only 4 digit year using regex
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $date)) {
    $dateObj = DateTime::createFromFormat('n/d/Y', $date);
    if ($dateObj === false) {
      throw new Exception("Not a valid date");
    }
    // convert it to 2 digit year
    echo $dateObj->format('n/j/y');
}

Here's how it can apply to your problem
<?php
    foreach($header as $field){
        if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $field)) {
            $dateObj = DateTime::createFromFormat('n/d/Y', $field);

            if ($dateObj === false) {
                throw new Exception("Not a valid date");
            }
            // convert it to 2 digit year
            $field = $dateObj->format('n/j/y');

            if($insert){
                $days[] = ["date" => $field, $type => $value[$field]];
            }
            else{
                $date_index = array_search($field, array_column($globalData[$index]['data'], 'date'));

                $globalData[$index]['data'][$date_index][$type] = $value[$field];
            }
        }
    }


Q:

Why did Jon and the Wildlings travel on the north side of the wall when they arrived back at Castle Black from Hardhome

In Game of Thrones season 5 episode 9 titled "The Dance of Dragons" Jon and company arrive at Castle Black after a disastrous battle against the White Walkers at Hardhome. They leave the battle at Hardhome on boats. So they most likely stopped off at Eastwatch by the Sea and marched towards Castle Black. Here is a map of Westeros for reference:

Theoretically when they arrived at Eastwatch it would make more sense for them to travel to Castle Black on the southern side of the Wall. But in the show we see Jon and company arrive back at Castle Black but they are on the northern side of the Wall. Why did they do this? It doesn't make a lick of sense. The White Walkers and the wights are all north of the Wall. They faced potentially more attacks by traveling on the north side of the Wall. Eastwatch and Castle Black are around a 100 miles apart so it would've taken several days to make that journey. That would've left them in danger by being on the north side of the Wall and they could've gotten attacked again by the White Walkers and the wights.
It just doesn't make logical sense to me. It feels like the writers only did this to falsely create dramatic tension when Ser Allister Thorne hesitates on whether or not to let Jon and company through the main gate back into Castle Black.
Is this just bad writing by the TV show writers? Or am I missing something? Cause for Jon to lead his people along the north side of the wall just makes him seem dumb.

A:

Well, my answer is not verified by any official source yet according to me it makes much logical sense so as justify their choice to travel from the North side of the wall to reach Castle Black. All above comments assume the premise that they reached Eastwatch first and then started marching towards Castle Black but it nowhere confirmed that they landed in Eastwatch. They might have landed as soon as they were far enough from white walkers because Stannis's ships could support a limited number of wildlings also some of them were on small boats( like Jon himself) so they couldn't travel that long distance on the water. And also WUN WUN wouldn't have walked the whole way to Eastwatch on water. So since they landed at North they arrived at the North gate of Castle Black.
Alternatively, let's assume they did reach Eastwatch after that if they chose South path they would have to face people of The Gift and Mole Town where wildlings already have a bad reputation owing to the fact that they ransacked many villages around the wall so these people can be potential threats, on the other hand, Jon knows that white walkers are far and the North path is clear of any obstacle or potential enemies so they chose that way.
And Lastly I agree with you that irrespective of their choice of the path the writers wanted to show Alliser's disagreement with Jon's decision so they just staged that Castle Black scene.


Q:

Axios method is passing item as null, instead of the actual value to my mongoose route

My Axios method is passing the item.GroupID as Null it seems, it successfully finds the item in my database using the item.id however.
Axios Method:
export const updateGroupID = item => dispatch => {
  axios.post(`/api/users/${item.id}/update`, item.GroupID).then(
    res =>
      dispatch({
        type: GROUPID_UPDATE,
        payload: res.data
      }),
    console.log(item.id)
  );
};

Mongoose Route:
router.post("/:id/update", (req, res) => {
  Users.findByIdAndUpdate(
    req.params.id,
    {
      $set: { GroupID: req.body.GroupID }
    },
    { new: true },
    (err, user) => {
      console.log("Triggered Update");
      if (err) res.send(err);
      else res.send("Account GroupID Updated" + " " + user);
    }
  );
});

How I'm calling the Axios method in React:
<button onClick={()=> {
      const updatedID = {
         id: this.props.user.user.UserId,
           GroupID: this.state.GroupID
      };
      this.props.updateGroupID(updatedID);
      }}
>join group</button>

A:

Axios by default will serialize requests as JSON, but you dont pass a valid JSON payload i.e.
axios.post(`/api/users/${item.id}/update`, item.GroupID)

Should be
axios.post(`/api/users/${item.id}/update`, { GroupID: item.GroupID })


Q:

How to automatically run Python script AFTER Raspberry Pi fully boots?

My script is /home/hello.py and it is using the Bottle web framework.  My script needs to run after Raspberry Pi has connected to my local network.  If I try to automatically run it on the boot, it doesn't work because the network connections just aren't ready yet.
I know I can I use "crontab -e" and add @reboot sleep 60 seconds -- but I don't think a sleep is too reliable.
All other "run script on boot" questions I've seen don't help because they run the scripts too early in the bootup process.
Is there anyway to check if the raspberry pi has connected and then have my python script automatically run?

A:

You may add your code at "/etc/network/if-up.d/upstart" just after "all_interfaces_up" like this:
all_interfaces_up() {
    python /your/code/path/codename.py
    # return true if all interfaces listed in /etc/network/interfaces as 'auto'
    # are up.  if no interfaces are found there, then "all [given] were up"

Where "/your/code/path/codename.py" is your code location


Q:

Fluid navigation items of different widths with equidistant spacing

I'd like to create a fluid horizontal navigation list of links, where the nav links are evenly spaced and take up the full width of the enclosing container . Nav links are all different widths. The first link should be left-aligned and the last link should be right aligned.
I've had limited success using techniques such as:
ul {display: table;width: 100%;}
li {display: table-cell;}
a {display: block;}

and also using
ul {text-align: justify}
li {inline-block }

but no code I've written seems to deal at all well with elements that are different widths. The spacing does not seem to stay equal as the nav is resized.
I need the nav to be fluid, first and last elements to be flush against the edge of the containing ul and for the elements to be equidistant from each other

A:

I thought about this for a while and came up with two reasonable approaches, both of which are pretty good but not exactly pixel perfect.  One is CSS based only and the second is aided by jQuery (JavaScript).
CSS Approach - pretty good approximation
Consider the following HTML:

Home

Collections

About Us

Slocklists

Trade Enquiries

Press

Contact Us

I added some classes as hooks for the styling.
The CSS is as follows:
.nav.ex1 {
    outline: 1px dashed blue;
    width: 100%;
    margin: 0;
    padding: 0;
    display: table;
}
.nav.ex1 li {
    display: table-cell;
    outline: 1px dotted gray;
    width: 20%;
    white-space: pre;
    text-align: center;
}
.nav.ex1 li.first {
    width: 1%;
}
.nav.ex1 li.last {
    width: 1%;
}
.nav.ex1 li.tight {
    width: 1%;
}

In Example 1, the ul.nav parent container uses display: table and width: 100%.  The child li elements are table-cell's.  I added white-space: pre to prevent some of the links from wrapping into two lines, and text-align: center to keep the text centered.
The trick is to force some of the table-cell's to shrink-to-fit the text, and you can do this by setting width: 1% which is non-zero but too small to hold the text (unless your screen is 10,000 pixels wide).  I shrink-to-fit the first and last cells which forces them to align to the left and right edges of the parent container.  I then force every other table-cell to shrink-to-fit by added the .tight class.
The remaining table's cells will have a width of 20% which will keep them evenly spaced between their two nearest neighbors.  HOWEVER, there will be some slight variation in spacing among the links in the row, which is why I call it an approximation.
jQuery Aided Solution
In Example 2, the markup is essentially the same and the CSS is:
.nav.ex2 {
    outline: 1px dashed blue;;
    margin: 0;
    padding: 0;
    display: block;
    overflow: auto;
    width: 100%;
}
.nav.ex2 li {
    float: left;
    display: block;
    outline: 1px dotted gray;
    width: auto;
}

In this case, the li elements are floated left and I use width: auto.
The trick is to calculate the magic left-margin value and apply it to all the li elements except for the first one.
The jQuery action is:
$(window).resize(function () {
    navResizer();
});

// On load, initially, make sure to set the size.
navResizer();

function navResizer() {
    var $li_w = 0;
    var $ul_w = $(".nav.ex2").innerWidth();

    $( ".nav.ex2 li" ).each(function( index ) {
        $li_w += $(this).innerWidth();
    });

    var li_margin = Math.floor(($ul_w-$li_w)/6);
    $(".nav.ex2 li").not(".first").css("margin-left",li_margin);
    $("p.note").text( "Widths: ul.nav: " + $ul_w + " all li: " + $li_w + " Left margin: " + li_margin);
}

Basically, the action calculates the width of ul.nav ($ul_w), and the total widths of all the li child elements ($li_w).
The left-margin is calculated by ($ul_w - $li_w)/6 where 6 is the number of gaps between the 7 links.
The key line of code is: $(".nav.ex2 li").not(".first").css("margin-left",li_margin);
I use .not(".first") to omit the first li element and then .css to set the left margin.
The one slight defect is at the far right where the link is not quite right justified, but you can fix that by floating the last li to the right.
For the most part, if your link texts were similar in length, you would be hard pressed to distinguish the two.  Both approaches are not quite pixel perfect, but pretty good.
Fiddle:  http://jsfiddle.net/audetwebdesign/xhSfs/
Footnote
I tried some other approaches using text-align: justify and inline-block, but the CSS engine does not treat inline-blocks like regular words, so will not justify a line of inline-blocks.
Setting left-margin to a % value will not quite work at some window widths and the right-most link will not be on the edge as desired.
The jQuery approach has been tried before, see:
Evenly-spaced navigation links that take up entire width of ul in CSS3

A:

You can use text-align: justify; and ignore the last left-justified row. #last is invisible and takes up the last row because of padding-left: 100%;: http://jsfiddle.net/mwRbn/
if you want to align the text of the menu vertically, use height in combination with line-height:
ul#nav {
  text-align: justify;
  width: 100%;
  background: yellow;
  height: 2em;
  line-height: 2em;
}

http://jsfiddle.net/mwRbn/1/. Do you need a IE<8 hack?


Q:

How do I correctly access and iterate over multidimensional arrays in Ruby?

I have this block of code:
super_heroes = [
    ["Spider Man", "Peter Parker"],
    ["Deadpool", "Wade Wilson"],
    ["Wolverine", "James Howlett"]
]

super_heroes.each do |sh|
    sh.each do |heroname, realname|
        puts "#{realname} is #{heroname}"
    end
end

The output is this:
 is Spider Man
 is Peter Parker
 is Deadpool
 is Wade Wilson
 is Wolverine
 is James Howlett

But I wanted to be this:
Peter Parker is Spider Man
Deadpool is Wade Wilson
Wolverine is James Howlett

After hours of iterating the code, I still couldn't figure it out. I would appreciate if someone could put me in the right direction and explain what I'm doing wrong. Thanks!

A:

Do as below :
super_heroes = [
    ["Spider Man", "Peter Parker"],
    ["Deadpool", "Wade Wilson"],
    ["Wolverine", "James Howlett"]
]

super_heroes.each do |heroname, realname|
   puts "#{realname} is #{heroname}"
end

# >> Peter Parker is Spider Man
# >> Wade Wilson is Deadpool
# >> James Howlett is Wolverine

What happened with your code ?
super_heroes.each do |sh| # sh is ["Spider Man", "Peter Parker"] etc..
    # here **heroname** is "Spider Man", "Peter Parker" etc.
    # every ietration with sh.each { .. } your another variable **realname**
    # is **nil**
    sh.each do |heroname, realname|
        puts "#{realname} is #{heroname}"
        # as **realname** is always **nil**, you got the output as
        # is Spider Man
        # is Peter Parker
        # .....
        # .....
    end
end


Q:

Modify rails link_to helper

I found somewhere what :back option in link_to helper has this code:
@controller.request.env["HTTP_REFERER"] || 'javascript:history.back()
where i can change it?

A:

It is actually uses url_for helper. You can override it in a helper. For example, put it in application_helper.rb in your Rails app:
def url_for(options = {})
  if options == :back
    # replace this with your code
    controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
  else
    super(options)
  end
end


Q:

How do I get vlc in the context menu in Nautilus?

When right-clicking on a directory once I got an entry "open with vlc". Now with precise this entry is gone. How can I get it back?
edit: Yes I have it in the submenu "open with". But how can I get it in the top menu?

A:

Using Ubuntu-tweak

First install Ubuntu-tweak

How do I install Ubuntu-Tweak?

Then open it by typing "Ubuntu-tweak" on the dash

After opening Ubuntu-tweak, go to the Admin tab

Then Go to the File type manager option

In this section, do these:

Select a catagory of media types, such Audio or Video
Select a type of the file, such as mp3, mkv etc
Double click the currently associated application such as Totem or something
In the new opened small window, Select VLC media player and close it.

Then close the Ubuntu-tweak and see the changes by doing a Right-Click.

Instruction for Directory: After subsequent comment by the OP, I realized that, he wanted to enable an entry in the directory with "Open with VLC media player". (And OP done this, before I edit the answer. ;P).
To do so, Follow the steps from 1-5. In the step 5, the procedures are slightly changed. These are:

Select the catagory All
Select the file type Folder
Double Click it to bring a new window. In this window, do these:

Remove all entries except Files from there by selecting one and then pressing Remove button.
After removing all except Files entries, Press Add button and Select the VLC media player from the new window and pressing Add button there. Remember to select the Files entry as default before closing this window.
The final file type choosing window should look like this

Note that, in the image, Files entry is selected to be the default.
Close all windows and close the Ubuntu tweak.

That's it.
If you ever wanted to revert the change, open Ubuntu-tweak and select the changed file type and Press the Reset button at the bottom-right position of Ubuntu tweak. All settings will be restored as before.


Q:

Offline Web Application HTML5 on Android

I want to develop a HTML5 Web App.
I read that in HTML5, you can use the new feature "Offline Web Applications"
With the *.manifest file
I read an article from november 2010, that this feature only works on the iOS platform.
Does it work on Android now?

A:

Yes. It works on Android as well as iOS and most desktop browsers. You don't need PhoneGap unless you want to access native features or deploy to the App store.
UPDATE:
Check out this chapter from Jonathan Stark's book: Building Android Apps with HTML, CSS, and JavaScript.


Q:

jQuery -> Selected Element to HTML

I am trying to wrap specific elements in a box if the visitor is using < IE9 so I can apply a box shadow across all browsers.
Unfortunately I cannot quite work out how to do it. Does anyone know how to convert the selected element back into HTML?

The script is printing out [object Object]. .html() doesn't work because that is basically innerHTML. Is there a jQuery function that achieves this?

A:

Just use .wrap
$('img').wrap('
');

Example - http://jsfiddle.net/BTJmn/


Q:

Is it useful to extend List in this case?

Consider I have the following code:
public interface Drawable {
    public void compileProgram();

    public Program getProgram();

    public int getDataSize();

    public FloatBuffer putData(final FloatBuffer dataBuffer);

    public int getDataMode();

    public void draw(final int offset);

    public void delete();

    public static int countDataSize(final Collection<Drawable> drawables) {
        return drawables.stream()
                .mapToInt(Drawable::getDataSize)
                .sum();
    }

    public static FloatBuffer putAllData(final List<Drawable> drawables) {
        FloatBuffer dataBuffer = BufferUtils.createFloatBuffer(countDataSize(drawables) * 3);
        for (Drawable drawable : drawables) {
            drawable.putData(dataBuffer);
        }
        return (FloatBuffer)dataBuffer.clear();
    }

    public static void drawAll(final List<Drawable> drawables) {
        int offset = 0;
        for (Drawable drawable : drawables) {
            drawable.draw(offset);
            offset += drawable.getDataSize();
        }
    }

    public static void deleteAll(final List<Drawable> drawables) {
        drawables.stream().forEach(Drawable::delete);
    }
}

and
public class Terrain implements Drawable { ... }

public class Floor implements Drawable { ... }

And I use it as the follows:
private final Terrain terrain;
private final Floor floor;
private final List<Drawable> drawables;

public FPSGameController(final int screenWidth, final int screenHeight, final boolean debug) {
    super(screenWidth, screenHeight, debug);

    this.terrain = new Terrain();
    this.floor = new Floor();
    this.drawables = new ArrayList<>();

    drawables.add(terrain);
    drawables.add(floor);
}

...

@Override
protected void render(final double msDelta) {
    super.render(msDelta);

    glClearColor(25f / 255f, 25f / 255f, 112f / 225f, 1.0f);
    glClearDepthf(1f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Drawable.drawAll(drawables);
}

Would it then be a correct approach to create a class:
public class DrawableList extends List<Drawable> { ... }

that implements the functionality that is currently static in the Drawable interface?
Also: Does my implementation currently perform some practice that generally is against coding standards?

A:

The usage of static methods in your interface Drawable seems good. As I know, it is possible to write static methods into interfaces (with Java 8) in order to avoid static classes like Collections or whatever.
To answer your question about the DrawableList, it is probably a bad idea. There are two reasons:

You are manipulating a lot of List<Drawable>, obviously. But when you want to implement an ArrayList, a Stack, a LinkedList or whatever, to get better performances, you will be happy to keep your current implementation.
If you extends List<Drawable>, remember you will never change this in your program without a lot of refactoring. And the day you need to extend an other class (for better reasons), you can do nothing.

Nevertheless, you can create an object DrawableList, which will manipulate a list:
public class DrawableList {
    private List<Drawable> list;
}

And in this class, you can call List methods by defining your own methods.


Q:

Eclipse GEF/Draw2d: Bounds vs. Constraints

Can someone explain the difference/relationship between bounds and constraints in Draw2d?
I'm trying to set up a GEF editor where instances of the same EditPart class are nested inside each other (I can post a simplified version of the code if necessary, but my question is really just conceptual).  Each figure has an XYLayout and I'm setting the bounds and constraints (Rectangles) of each figure in refreshVisuals.
Right now my bounds and constraints are the same for each figure.  Is that correct?  Since I'm using XYLayout, are the coordinates of the bounds relative to the parent Figure?  How about for the constraints?

A:

The bounds of a child figure are only relative to the parent figure, if isCoordinateSystem() of the parent returns true - which is hardly ever the case. So in practice bounds are absolute coordinates.
The rectangles you provide as constraints in XYLayout are expected to contain coordinates relative to the parent and the layout then converts those relative coordinates in a way that is appropriate. If e.g. no figure in the parent chain has a local coordinate system, then the resulting bounds will be absolute coordinates.


Q:

java exception handling nested methods

Is it good design to catch exceptions in a method where enclosed methods already catch the exception? For example, in the following code a public method calls 2 private methods. The private methods already catch any exception and print it:
/*The only thing this method does is call the enclosed methods.*/
public Object enclosingmethod()
{
    try
    {
       enclosedmethod1();
       enclosedmethod2();
    }
    catch (Exception e)
    {
       e.printstacktrace();
    }
}

private Object enclosedmethod1()
{
    try
     {
       //some logic
     }
     catch (Exception e)
     {
       e.printstacktrace();
     }
}

private Object enclosedmethod2()
{
    try
     {
       //some logic
     }
     catch (Exception e)
     {
       e.printstacktrace();
     }
}

A:

No, it is not good design. And especially in this case it is wrong, because you surround the calls of enclosedmethod1 and enclosedmethod2 in a catch block, but don't even throw an exception in these blocks, because all Exceptions are caught!
Especially not to catch the mother of all exceptions, java.lang.Exception.
But as always it depends. Ask yourself the question: what is supposed to happen when enclosedmethod1 encounters an exception? Should the code continue to be executed? because if you catch it, enclosedmethod2 will still be executed. Should it? I can't tell you, but maybe you can, because you know what enclosedmethod1 and enclosedmethod2 are supposed to do.
There is no general answer to this question, because it depends on your requirements.
But as always, take your time to think about exception handling.


Q:

doMC: Only together with foreach?

I want to run an R script to use the reversed feature elimination from the caret package on a computer cluster. Ideally I would like to run it on multiple cores in parallel. In the script of a coworker, I found the use of the doMC package. I read that this package is used together with the foreach package. But in the script I got, there is simply the library imported and in the line before the rfe command there is a registerDoMC(5). There is not a single use of foreach in the whole script.
Will the doMC do anything here or does it only work together with foreach?
Is there a way to distribute the resource consuming rfe process on multiple cores?

A:

Read the documentation:

rfe can be used with "explicit parallelism", where different resamples
  (e.g. cross-validation group) can be split up and run on multiple
  machines or processors. By default, rfe will use a single processor on
  the host machine. As of version 4.99 of this package, the framework
  used for parallel processing uses the foreach package. To run the
  resamples in parallel, the code for rfe does not change; prior to the
  call to rfe, a parallel backend is registered with foreach (see the
  examples below).

So, caret::rfe uses foreach internally.


Q:

Unicode support of PostgreSQL and its performance

How is the Unicode support of PostgreSQL?
If I want to save Unicode data does it have to go through the conversion process while storing and retrieving? If yes then what is the performance of such conversion?
If there is such a conversion, will it come into play when storing simple ASCII data?

A:

Unicode encoding support in PostgreSQL is stellar and is implemented using the UTF-8 character encoding.
If the client uses a different encoding than the server, automatic character set conversion occurs, paying a negligible performance penalty.
ASCII data does not require conversion to the UTF-8 character encoding, so no performance penalty there.
Please refer to the PostgreSQL Localization documentation for further information.


Q:

VBA Excel Dynamically Display Added Results

So I am modeling my question with a simple Grocery List applications.
Program GUI:

Now what I want is for the Customer to enter: Eggs, Milk, and Bread and for that to enter and output to a .txt file.
Current Code:
Private Sub CreateList_Click()

Dim myFile As String, myString As String
myFile = "C:\Reformatted.txt"
Open myFile For Output As #1

myString = First.Value + Second.Value + Third.Value + Fourth.Value + Fifth.Value

Print #1, myString

Close #1
Shell "C:\Windows\Notepad.exe C:\Reformatted.txt", 1

End Sub

Desired Operation:
What I want to happen is that ther enter there first 5 items. Then it prompts them if they want another 5. If they do then they can add another line.
So I understand that I can add a MsgBox in VB and just design a while loop for that. My question is how to display the results of their first/previous submissions?
Desired Result:

I understand that VB stores the values as variables, but how can I show them to the user while they still have a chance to enter more entries. Also how to add all this with the preferred formatting to a notepad file?
----------------------------After Miss Palmer's Answer--------------------------
Private Sub AddEntry_Click()

Dim UserEntry As String

UserEntry = First.Value + DDPP.Value + Filer.Value + EntryNumber.Value

myString = myString & Chr(13) & UserEntry

GroceryList.UserDisplay.Caption = "You have entered:" & myString

End Sub

Scenario 1 - First Addition

Scenario 2 - Second Addition

The two additions should be placed one after the other. But currently it just replaces it.

A:

You can update a label on the form on each iteration of your while loop using something of the form:
FormName.LabelName.Caption = "you have entered:" & myString

and then add to the string each loop with
myString  = myString & First.Value + Second.Value + Third.Value + Fourth.Value + Fifth.Value

EDIT
myString  = myString & chr(13) & First.Value + Second.Value + Third.Value + Fourth.Value + Fifth.Value


Q:

How to fix Error: _registerComponent(...): Target container is not a DOM element. error?

I have compiled my project using Webpack. However, when I launch my html, only my background color displays but nothing else and I get the following error in the console:
Error: _registerComponent(...): Target container is not a DOM element.

This is my HTML:
<!doctype html>

    <link rel="stylesheet" type="text/css" href="cssWEB.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React App</title>

And my JS:
import React from 'react';
import ReactDOM from 'react-dom';
import {Element, scroller} from 'react-scroll';

const Component = React.createClass({
    componentDidMount: function() {
        scroller.scrollTo('myScroller', {
            duration: 1500,
            delay: 500,
            smooth: true
        });
    },

    render: function() {
        return (

              <link rel="stylesheet/less" href="style.less" type="text/css" />

              <link type="text/javascript" href="jscode.js"></link>

                My Page

 { this.messagesEnd = el; }}>

Resume

Work

Contact

              <Element name="link1">

              </Element>

aa

cc.i

        );
    }
});

ReactDOM.render(
  <Component />,
  document.getElementById("root")
);

What is wrong with my code that is raising this error?

A:

Because document.getElementById("root") would return a DOM element after the document has loaded, this suggests that your script runs before the DOM element has been created.
Looking at your HTML confirms this. You load bundle.js in the head, but at that point the document body has not loaded.
To solve this issue, you can move your script tag below the div element to ensure the element has been created by the time the script runs.
<!doctype html>

    <link rel="stylesheet" type="text/css" href="cssWEB.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React App</title>


Q:

1and1 hosting asp.net mvc 2 server error in '/' application

I am having a problem with a small website that I am creating in visual studio 2008, using asp.net mvc 2, and the hosting server 1and1.co.uk. I have no database within the website yet, as it is a work in progress, just need the site up and running properly.
The problem is that I even after uploading the published website to the account on 1and1, I still get the error:
"error in '/' application"
Im not too sure if it is the web.config file or not. From what I have seen on some forums and websites I can not seem to sort this problem out.
Can someone please help me out with this problem
Many thanks.

A:

Then its better to find out what you can run on your hosting, try first to run an empty web application without mvc and see if it runs.


Q:

What is the `Cd` command?

I was writing some code, navigating my computer (OSX 10.11.6) via the command line, like I always do, and I made a typo! Instead of typing:
cd USB

I typed
Cd USB

Nothing happened, but it didn't register as an invalid command. Perplexed by this, I did some investigating: I checked the man entry. There was no entry. I found the source file (/usr/bin/Cd) using which Cd, and then cated it:
#!/bin/sh
# $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $
# This file is in the public domain.
builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

What is this, and why is it here? How does it relate to freeBSD?
Any help would be amazing, thanks!

A:

macOS uses a case-insensitive filesystem by default[1]
, which can be misleading at times:
which Cd is effectively the same as which cd and which CD in terms of returning the (effectively) same file path.
Confusingly, even though all 3 command refer to the same file, they do so in a case-preserving manner, misleadingly suggesting that the actual case of the filename is whatever you specified.
As a workaround, you can see the true case of the filename if you employ globbing (filename expansion):
$ ls "$(which Cd)"*  # could match additional files, but the one of interest is among them
/usr/bin/cd  # true case of the filename

Bash (the macOS default shell) is internally case-sensitive.
That is, it recognizes cd as builtin cd (its built-in directory-changing command).
By contrast, it does NOT recognize Cd as that, due to the difference in case.
Given that it doesn't recognize Cd as a builtin, it goes looking for an external utility (in the $PATH), and that is when it finds /usr/bin/cd.

/usr/bin/cd is implemented as a shell script, which is mostly useless, because as an external utility it cannot affect the shell's state, so its attempts to change the directory are simply quietly ignored.
(Keith Thompson points out in a comment that you can use it as test whether a given directory can be changed to, because the script's exit code will reflect that).
Matt's answer provides history behind the inclusion of the script in FreeBSD and OSX (which mostly builds on FreeBSD), but it's worth taking a closer look at the rationale (emphasis mine):
From the POSIX spec:

However, all of the standard utilities, including the regular built-ins in the table, but not the special built-ins described in Special Built-In Utilities, shall be implemented in a manner so that they can be accessed via the exec family of functions as defined in the System Interfaces volume of POSIX.1-2008 and can be invoked directly by those standard utilities that require it (env, find, nice, nohup, time, xargs).

In essence, the above means: regular built-ins must (also) be callable stand-alone, as executables (whether as scripts or binaries), nut just as built-ins from within the shell.
The cited regular built-ins table comprises these utilities:
alias bg cd command false fc fg getopts jobs kill newgrp pwd read true umask unalias wait
Note: special built-in utilities are by definition shell-internal only, and their behavior differs from regular built-in utilities.
As such, to be formally POSIX-compliant an OS must indeed provide cd as an external utility.
At the same time, the POSIX spec. does have awareness that at least some of these regular built-ins - notably cd - only makes sense as a built-in:
"Since cd affects the current shell execution environment, it is always provided as a shell regular built-in." - http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html
Among the regular built-in utilities listed, some make sense both as a built-in and as an external utility:
For instance kill needs to be a built-in in order to kill jobs (which are a shell-internal concept), but it is also useful as an external utility, so as to kill processes by PID.
However, among the regular built-in utilities listed, the following never make sense as external utilities, as far as I can tell Do tell me if you disagree
, even though POSIX mandates their presence:
alias bg cd command fc fg getopts jobs read umask unalias
Tip of the hat to Matt for helping to complete the list; he also points that the hash built-in, even though it's not a POSIX utility, also has a pointless script implementation.

[1] As Dave Newton points out in a comment, it is possible to format HFS+, the macOS filesystem, in a case-sensitive manner (even though most people stick with the case-insensitive default). Based on the answer Dave links to, the following command will tell you whether your macOS filesystem is case-insensitive or not:
diskutil info / | grep -iq '^\s*Name.*case-sensitive*' && echo "case-SENSITIVE" || echo "case-INsensitive"

A:

What is this?
The script itself is a portable way to convert a command, even with random upper casing, into the equivalent shell builtin based on the exec paths file name, that is any part of the string after the final / in the $0 variable). The script then runs the builtin command with the same arguments.
As OSX file systems are case insensitive by default, /usr/bin/cd converts running Cd, CD, cD and any form of cd with a / fs path (like /usr/bin/cd) back to the shell builtin command cd. This is largely useless in  a script as cd only affects the current shell it is running in, which immediately closes when the script ends.
How does it relate to freeBSD?
A similar file exists in FreeBSD, which Apple adapted to do case conversion. Mac file systems by default are case insensitive (but case preserving).
The $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $ header is the source information in the file.
Most of the underlying OSX system comes directly from FreeBSD or was based on it. The Windowing system on top of this and the Cocoa app layer is where OSX becomes truly Apple. Some of the lower level Apple bits have even made it back into FreeBSD like Clang and LLVM compiler.
Why is it here?
The earlier FreeBSD svn commits shed a bit of light:

A little bit more thought has resulted in a generic script which can
  implement any of the useless POSIX-required ``regular shell builtin''
  utilities...

Although most builtins aren't very useful when run in a new shell via a script, this compliance script was used for the commands alias bg cd command fc fg getopts hash jobs read type ulimit umask unalias wait. POSIX compliance is fun!


Q:

What's best practice in terms of handling Gift Aid within CiviCRM

I'm just setting up the 3.0 beta Gift aid extension (https://github.com/compucorp/uk.co.compucorp.civicrm.giftaid and https://civicrm.org/extensions/gift-aid-extension-uk), as provided by Compucorp (and for which many thanks) for CiviCRM 4.6.
However I'm a tad confused, because there's also the Gift Aid Online Submission extension from Veda Consulting (https://civicrm.org/extensions/uk-hmrc-online-gift-aid-submission). Studying the available documentation, neither extension appears to reference or make mention in any way of the other. I've a vague memory from CiviCon London a few years back that the online submission extension builds on the Compucorp extension by enabling straightforward submission direct to HMRC, but I'm not clear. Can anyone cast any light?
If I can get some clarity, through my own experience and that of other folks that have gone through this I'll be happy to write it up in a way that might be helpful to other users.

A:

You are correct - the Veda extension is for submitting the Gift Aid application to HMRC and the Compucorp one does the rest. It's a shame this isn't better documented. Be careful of the version of the Compucorp one though, as I don't believe the one of the Civi extensions page works with 4.6 - get a working version from Git here


Q:

Artificially populate HttpContext object in a Console application

I am writing a wrapper library for log4net. This library should be able to capture Context information such as querystring, cookie, form fields etc. etc.
I am invoking this wrapper class from Console application as opposed to TDD class.
Is there a way to populate HttpContext object inside a Console application as follows?
HttpContext c = new HttpContext(null);
c.Request.QueryString.Keys[1] = "city";
c.Request.QueryString[1] = "Los Angeles";
c.Request.QueryString.Keys[2] = "state";
c.Request.QueryString[2] = "CA";

And then retrieve it as follows?
Console.WriteLine(context.Request.QueryString.Keys[1]);

I am getting the following exception when I attempt the above code.
Property or indexer 'System.Collections.Specialized.NameObjectCollectionBase.KeysCollection.this[int]' cannot be assigned to -- it is read only

A:

you can read here on using Moq to fake it out:
http://o2platform.wordpress.com/2011/04/05/mocking-httpcontext-httprequest-and-httpresponse-for-unittests-using-moq/


Q:

When aren't Christoffel symbols symmetrical with respect to bottom indices, and why?

When aren't Christoffel symbols symmetrical with respect to the bottom indices? Why isn't the symmetry of second derivatives true in this case?

A:

Let $\pi:E\rightarrow M$ be an arbitrary vector bundle, not necessarily the tangent bundle $TM$ of $M$. Locally, say over an open subset $U\subset M$, one can choose a family of point-wise linearly independent sections $\{E_i:U\rightarrow E\}$, which is called a local frame in $E$ (over $U$). Then each section $X:U\rightarrow E$ can be uniquely represented in terms of $\{E_i\}$
$$
X=X^i E_i \quad \mbox{(Einstien summation assumed)}
$$
In presence of a connection $\nabla$ in $E$ the covariant derivatives can be computed in terms of the Christoffel symbols of $\nabla$ with respect to the local frame $\{E_i\}$ defined as
$$
\nabla_{E_i}{E_j} = \Gamma^k_{ij} E_k
$$
In general, the Christoffel symbols need not to be symmetric since torsion may not vanish, as noted by the commenters.
For the case of Riemannian manifolds, the Riemannian metric $g$ induces a preferred connection in the tangent bundle which is called the Levi-Civita connection. We prefer this one because it is torsion-free (the torsion tensor $T(X,Y)=\nabla_X Y - \nabla_Y X -[X,Y]$ vanishes) and the metric tensor is parallel w.r.t. to it: $\nabla g =0$.
Connections in the tangent bundle are sometimes termed linear.
In a coordinate patch $(U,x^i)$ we have the standard coordinate frame $\{ \partial_i \}$ (of the tangent bundle) where vector fields $\partial_i$ act as partial derivatives on functions. This implies that a linear connection is torsion-free if and only if the Christoffel symbols with respect to any coordinate frame (!) are symmetric  w.r.t the bottom indices (see J.Lee, Riemannian manifolds. An introduction to curvature, Springer 1987, p.63) (Hint: $[\partial_i, \partial_j]=0)$


Q:

In Lisp, how do you call a function from a macro, by name passed as an argument?

In Lisp, how do you call, from a macro, a function whose name is the symbol value of a symbol? I might be wrong but I think I'm right that a symbol is a variable.
Here is what I currently have:
(defmacro cfunc (a b) (list a b))
(defparameter foo 'my-func)
(defun my-func (data) '(some-code))
(cfunc foo data) ;does not work
(cfunc my-func data) ;works

I'm thinking I need to add some special character in front of foo to evaluate to its symbol value before being treated as a function. (cfunc foo data) creates and calls the function (foo data) instead of (my-func data). I suppose I could change the function defining in cfunc instead.
#'foo doesn't work, that gives (function foo) which cfunc returns and calls ((function foo) data). (symbol-value foo) can't work either. So I'm thinking I can't change what is given to cfunc but I can change the code of the function cfunc makes.
If someone has a specific page of a resource that tells me about evaluation and expansion using defmacro or the specifics of the special characters like # and ' or know the keywords I should be looking up, I'd appreciate it if that could be shared as well.

A:

First, in the form (cfunc foo data), to what do you expect that data refers? I don't see any definition of it here. It's only mentioned incidentally as a parameter to the my-func function, which doesn't come into play for your expansion of cfunc. Perhaps you expect data to be available later as a special variable.
In any case, the problem you're running into is that Common Lisp is a "Lisp-2"; a variable present at the head of a function form doesn't automatically have its function cell accessed to coerce it to a function. In your case, foo is not a function bound in the environment; it's a variable whose value is a symbol (my-func)—one that in turn is bound to a function. To navigate this extra level of indirection, you have to request that that symbol's function cell be accessed, either via funcall or, in other cases, function.
Here are a few observations from the REPL:
> (symbol-value 'foo)
MY-FUNC
> (ignore-errors (symbol-function 'foo))
NIL
#<UNDEFINED-FUNCTION FOO {1004E22D23}>
> (fboundp 'foo)
NIL

> (ignore-errors (symbol-value 'my-func))
NIL
#<UNBOUND-VARIABLE MY-FUNC {1005324E93}>
> (symbol-function 'my-func)
#<FUNCTION MY-FUNC>
> (fboundp 'my-func)
T

Here we see that the symbol foo has a value binding—meaning it's a variable—but it has no function binding. Following foo through to my-func, we see that my-func has no value binding, but it does have a function binding.
To wrap up, your cfunc macro needs be written as follows:
(defmacro cfunc (a b)
  (list 'funcall a b))

Alternately, you can write it like this:
(defmacro cfunc (a b)
  `(funcall ,a ,b))

You mentioned originally that the form
(cfunc my-func data)

works as intended. With my proposed revision above, it won't work any longer, because now my-func is being treated as a value to be evaluated as an argument to funcall, when in fact it has no value cell (as it's a function). Hence, you'll have to adapt the form to the following:
(cfunc #'my-func data)

That's saying, "Look up the symbol 'my-func' in the function namespace, grab its value, and supply that function as an argument."
For a more precise treatment on the difference in handling such symbols-pointing-to-functions in Lisp-1 and -2, see Gabriel's Technical Issues of Separation in Function Cells and Value Cells—in particular, section 5, "Notational Simplicity".


Q:

Why is BufferedWriter not writing to file?

I have this code:
    String[] strings = {"Hi" , "You", "He", "They", "Tetrabenzene", "Caaorine", "Calorine"};

    File file = new File("G:\\words.txt");
    FileWriter fWriter;
    BufferedWriter bWriter;

    try {
        if((file.exists())) {
            file.createNewFile();
        }
        fWriter = new FileWriter(file.getAbsoluteFile(), true);
        bWriter = new BufferedWriter(fWriter);

        //Convert Result objects to JSON and write to file
        for(int j = 0; j < strings.length; ++j) {
            bWriter.write(strings[j]);
                bWriter.newLine();
                System.out.println("done");
        }
    }
    catch(IOException e) {e.printStackTrace();}

I have pretty much the same code 2 or 3 times before this and BufferedWriter is writing perfectly.  But for some reason when I get to this code it doesn't write.  I've been looking for things that might be wrong but I can't change something and test it quickly as the program takes 10 minutes just to get to this part.
Also, the program prints "done" to the console so I know it is going into the for loop.
Any ideas as to what I'm doing wrong?

A:

Call bWriter.flush() when you want your data to actually be flushed to your file on disk.
Or just call bWriter.close() when you're done working with your writer.
The bWriter.close() call will call bWriter.flush() internally.


Q:

Incorrect field type mapping SubSonic 2.2, SQLite 3

I have a boolean (BOOL) type field in the SQLite table.
In the SubSonic generated DAL it is represented as string (instead of bool).
It is weird.
How it can be managed? Please, help.
alt text http://dl.dropbox.com/u/3882061/sqlite.GIF

A:

I maybe wrong on this, I have only used Subsonic 2.2 with SQL2008 but I would recommend looking at the source for Subsonic, namely SQLLiteDataProvider.cs and reviewing the DbType function.
It seems to recognise the type Boolean but not Bool and the default when it does not recognise your type is to resort to String.
Hare is the code in question from that function
 switch(sqliteType.ToLowerInvariant())
            {
                case "text":
                case "char":
                case "nchar":
                case "varchar":
                case "nvarchar":
                    return DbType.String;
                case "boolean":
                case "bit":
                    return DbType.Boolean;
                case "bigint":
                case "int":
                case "integer":
                    return DbType.Int64;
                case "real":
                case "numeric":
                case "double":
                case "single":
                case "float":
                    return DbType.Single;
                case "smallint":
                    return DbType.Int16;
                case "date":
                case "time":
                case "datetime":
                case "smalldatetime":
                case "timestamp":
                    return DbType.DateTime;
                case "binary":
                case "blob":
                case "image":
                    return DbType.Binary;
                case "guid":
                    return DbType.Guid;
                default:
                    return DbType.String;
            }

I would recommend changing it, seeing if it works and then recommeding the change to the subsonic chaps.


Q:

An example that a $p$ adic Galois representation is crystalline but not $B_e$ admissible

$B_e=B_{\text{cris}}^{\phi=1}$, so if a $p$-adic Galois representation $V$ is $B_e$ admissible, then it is crystalline, so I want to know an example that $V$  is crystalline but not $B_e$ admissible.
Thanks!

A:

We have $(V \otimes B_e)^{G_K} = D_{\mathrm{cris}}(V)^{\varphi = 1}$. So any representation which is crystalline, but such that $\mathbf{D}_{\mathrm{cris}}(V)$ has zero $\varphi$-invariants, is an example of a representation which is $B_{\mathrm{cris}}$-admissible but not $B_e$-admissible.
For instance, taking $K = \mathbf{Q}_p$ and $V$ any non-zero power of the cyclotomic character) will do the trick -- note that $D_{\mathrm{cris}}(\mathbf{Q}_p(n))$ is 1-dimensional with $\varphi$ acting as multiplication by $p^{-n}$.
(Moral: although the ring $B_e$ is useful in many ways, it is too small for the category of $B_e$-admissible representations to be interesting.)


Q:

Reason linking to pthreads causes a change in program behavior?

When linking to pthreads I get unexpected behavior during program execution, the ncurses interface becomes unresponsive, but the program does not crash. This is without using any pthread functionality, no threading headers or anything related to threads, just linking.
Are there any reasons that linking to a library can change program behavior without issuing warnings?
Pertinent information:

ncurses is also linked to the executable.
Everything is in a namespace.
Tried on current gcc and clang.
No compiler/linker errors or warnings using -Wall.
Arch Linux.

Linking ncurses and pthread together works fine on a smaller test program I made. So what I am looking for are more places to look, it's a library project and the codebase is a good size, it is all plain C++14 except for a small component that uses the ncurses library.

A:

If you didn't changed anything in your code, didn't even include headers,  but behavior changed, then your project contains UB. Possible UBs defined in standard, that may cause this:

Defining ANY function or global variables that match by name ones contained in standard headers
Defining something in std namespace.
Usage old C standard headers mixed with new C++ headers
Usage of variables that were initialized with undetermined value.
Array bound breaches, that do not lean to page fault or other kind of catastrophic result, may cause program change behavior.
Illegal use of side-effects of operators, e.g.: a ^=b ^= a ^=b;

and so on.
I  recommend to check warnings, not only errors. There are certain warnings  that are actually signs of semantic error or UB. AT least for GCC. Many novice programmers just ignore warnings as non-essential. E.g. this kind sneaks in quite often:
const char a = 167;

if(a == 167)  // compiler makes warning here, a ==-89 in this example
{
    // code will never be executed or even compiled
}

The code compiles but doesn't execute in expected way.


Q:

Problem with making 1 bit RAM memory using transistors

I'm trying to make 1 bit RAM using four transistors (2 NOR gates).
I built two copies of the following circuit:

I connected a LED to the output "F". Also, I connected another LED to the output of the second circuit (because I built two identical copies) to test them before I continue.
The problem is that when I connect any input of both circuits to HIGH, the two LEDs turns off rather than one LED.
That means the outputs of the two circuits are somehow connected together. In other words, when the base of any transistor is HIGH, the transistor works as a short circuit (wire) for the 2 LEDs so that they both turn off.
I thought I was mistaken and completed the circuit as shown:

But the result is that the LEDs are always off.
What can I do to separate between the two outputs Q and Q'?
Does a floating input mean it is LOW?
Note: I used only R1 and R2, and I didn't use R, R3, and R4. I connect the bases of the transistors directly to the positive terminal ti make them HIGH.

A:

Well, @Michael George... I can't refuse such a tempting promise:)
You can build the most elementary memory cell only by two inverters (transistor switches). I do this every year with my students at the beginning of the laboratory exercise about latches in the laboratory of digital electronics (you can see how in this movie and also in this Wikibooks story written by my students). Here is the building "scenario".

To make a latch (flip-flop, memory cell, 1-bit RAM...), you need only a non-inverting amplifier - just connect its output to the input... and it will begin "memorizing"... keeping by itself at the "top" (+Vcc) or the "bottom" (ground). BTW this clever idea was proposed in 18th century by Baron Münchhausen... so that he can be considered as the inventor of the most elementary RAM cell:)
But, for some reasons, in electronics there are only inverting amplifying stages - a common-emitter amplifier, in your case. So, to make a non-inverting stage, you connect  (by the yellow wire, in the picture below) in succession (cascaded) two inverting stages, and then connect (by the black wire) the output of this non-inverting amplifier to its input. Actually the two stages are connected in a loop but for some reasons (maybe to hide the idea:) they draw this configuration as two cross-coupled stages. You should connect the base resistors R3, R4 to extend the small (0.7 V) input range of the the bipolar transistor up to Vcc (5 V). If you don't connect them, the forward-biased base-emitter junction (like a diode) will fix the collector voltage of the other transistor at +0.7 V, and your LEDs will never light (if connected to ground) or will ever light (if connected to Vcc).
You can drive this latch in various ways (as you can see in the movie):

The most correct of them is to connect the one end of the (red) wire to the ground and to touch the base of the turned-on transistor with the other end, or to touch the collector (the body, if it is made metallic) of the turned-off transistor (this is the role of your additional transistors T1 and T3, they act as the red wire).
An incorrect way is to connect the red wire to Vcc (as shown in the picture), and to touch the collector of the turn-on transistor... but it is interesting that it still survives:). It is extremely interesting to see why since exactly in this way the memory cells of today's modern RAMs are controlled...
And the most incorrect way is to touch the red wire directly to the base of the cut-off transistor (since you apply +5 V across the base-emitter junction that tries to fix it at 0.7 V). The result - more likely, either the transistor or the power supply will be damaged; that is why (to limit the current) you have to connect the base resistors R. But in the circuit shown in the movie, the transistors still survived when my students touched their bases by +5 V... it is interesting to see why...


Q:

Jquery date field change function working in Chrome but not in Mozilla

I want to get the date, month, the year from input date given by the user. but these function perfectly works in google chrome but they are not working in Mozilla firefox. But I need them in Mozilla also. Please could anyone help me.
$("#dob").change(function(){
    var birthday = $("#dob").val();
    var d=new Date(birthday.split("/").reverse().join("-"));
    var dd=d.getDate();
    var mm=d.getMonth()+1;
    var yy=d.getFullYear();
    var newdate=yy+"/"+mm+"/"+dd;

    alert(newdate);

    var datas = "birthdate=" + newdate;
    $.ajax({
        url: '/pages/verify',
        type: 'GET',
        data: datas,
        success: function(output){
            if(output.status == 0){
                information_alert("Sorry you are not eligible to access this site..");
            } else if(output.status == 1) {
                window.location = '/dashboard';
            }
        }
    });
});

I get this by using an alert
 NaN/NaN/NaN

A:

Try this...
you are using mm/dd/yyyy format as input and then reversing this with "-" results to yyyy-dd-mm which is invalid date format.

var birthday = '02/22/2017';
var d = new Date(birthday.split("/")[2] + "-" + birthday.split("/")[0] + "-" + birthday.split("/")[1]);
var dd = d.getDate();
var mm = d.getMonth() + 1;
var yy = d.getFullYear();
var newdate = yy + "/" + mm + "/" + dd;
alert(newdate);


Q:

MySQL to select row with unique column value comparing with other columns

I don't know how to explain this, I have a table with three column and I need to select rows with column value which is not repeated in other columns.
Table:

CREATE TABLE `new_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `col1` varchar(45) NOT NULL,
  `col2` varchar(45) NOT NULL,
  `col3` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `new_table` (`col1`, `col2`, `col3`) VALUES ('red', 'blue', 'red');
INSERT INTO `new_table` (`col1`, `col2`, `col3`) VALUES ('white', 'red', 'yellow');
INSERT INTO `new_table` (`col1`, `col2`, `col3`) VALUES ('red', 'red', 'red');
INSERT INTO `new_table` (`col1`, `col2`, `col3`) VALUES ('yellow', 'blue', 'black');

I tried with xor in where statement.
SELECT * FROM new_table WHERE
        col1 LIKE '%red%'
        xor col2 LIKE '%red%'
        xor col3 LIKE '%red%';

But I didn't get desired output
Output of this code

ID  COL1    COL2    COL3
2   white   red     yellow
3   red     red     red

Output which I need
ID  COL1    COL2    COL3
2   white   red     yellow

And what if I have N-Number of columns, I know this isn't a best database design.But just for knowledge.
SQLFiddle

A:

Something like this:
SELECT *
FROM new_table
WHERE CONCAT( col1,  ' ', col2,  ' ', col3 ) LIKE  "%red%"
AND col1 <> col2
AND col2 <> col3
AND col1 <> col3;


Q:

SSL Error on Heroku app

I cannot get ssl to work properly on my heroku app.
I have successfully add the crt key witch gives me:
Resolving trust chain... done
Updating SSL Endpoint aichi-7001.herokussl.com for mysite... done
Updated certificate details:
Common Name(s): mysite.com
                www.mysite.com

Expires At:     2013-11-03 23:59 UTC
Issuer:         /OU=Domain Control Validated/OU=Free SSL/CN=www.mysite.com
Starts At:      2013-08-05 00:00 UTC
Subject:        /OU=Domain Control Validated/OU=Free SSL/CN=www.mysite.com
SSL certificate is verified by a root authority.

but when i try to load the page on the browser, i get the following message:
This is probably not the site you are looking for!
You attempted to reach www.mysite.com.br, but instead you actually reached a server identifying itself as *.herokuapp.com. This may be caused by a misconfiguration on the server or by something more serious. An attacker on your network could be trying to get you to visit a fake (and potentially harmful) version of www.mysite.com.br.
You should not proceed, especially if you have never seen this warning before for this site.

Any ideias on where did I mistake?

A:

You need to add the domain www.mysite.com to your Heroku app like so:
$ heroku domains:add www.mysite.com

Added www.mysite.com to example... done


Q:

Is it possible to pass different url parameters to the individual endpoints in Camel Multicast EIP?

Here is the use case that I m trying solve - So this is an extension to the my earlier thread, Apache camel to aggregate multiple REST service responses
I've used a Multicast component with custom aggregation strategy to fork the incoming request to sub requests and aggregate their responses. Everything works fine till this.
Now for one of the use case I want the incoming URL parameters to be passes selectively to some of the sub services. ex:
Incoming request - http://[host]/my-service/scan?foo=a&bar=b&baz=c
My Multicast component looks like this -
<multicast strategyRef="myAggregationStrategy" parallelProcessing="true">
     <to REST_service_1"/>
     <to REST_service_2"/>
</multicast>

I want to pass only foo=a to service_1 endpoint and bar=b&baz=c to service_2 endpoint.
Now, with Multicast the same set of request query parameters are getting passed to both service_1 and service_2.  i.e. both service_1 and service_2 will receive foo=a&bar=b&baz=c (entire query params)
Option I m thinking (on high level) -
-to break the incoming url parameters and stick them as a headers then i can selectively use these headers to build CamelHttpQuery header for each individual "to service_call"
-But at the end, the Exchange is going to be shared among all the Multicast endpoints, so will this approach work at all?
-Or should I step back and think about different EIP altogether for this particular use case?
-Or I m thinking in a wrong direction :)
Appreciate the inputs! Thanks!

A:

You can use the recipient list EIP instead, then you can have 2 different uris for the REST services to call, but sending the same message as the multicast would do.
Recipient list also supports parallel and aggregation.
http://camel.apache.org/recipient-list.html
To compute the 2 uris for the rest services you can use a java bean and do a method call expresison, and just return a String with the 2 endpoints separated by comma (or a String[], or a List etc.)
<recipientList strategyRef="myAggregationStrategy" parallelProcessing="true">
     <method ref="myBean" method="whereToSend"/>
</recipientList>


Q:

Continue processing in spite of unavailable WCF Service

I have the following code courtesy of an answer posted by Jean-Michel Bezeau
bool isAlive = false;
string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex";
System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress));
ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]);
WCFService.IAlive accesService = factoryService.CreateChannel();
isAlive = accesService.IsAlive();

I would like my program to continue even if the WCF Service can't be reached so that I can notify someone via email and add it to a log. I thought of doing it like this:
bool isAlive = false;
try
{
    string fixedAddress = "http://localhost:8732/Design_Time_Addresses/WCFService/mex";
    System.ServiceModel.Description.ServiceEndpointCollection availableBindings = System.ServiceModel.Description.MetadataResolver.Resolve(typeof(WCFService.IAlive), new EndpointAddress(fixedAddress));
    ChannelFactory<WCFService.IAlive> factoryService = new ChannelFactory<WCFService.IAlive>(availableBindings[0]);
    WCFService.IAlive accesService = factoryService.CreateChannel();
    isAlive = accesService.IsAlive();
}
catch {}
finally
{
    if (isAlive)
    {
        //add success message to log
    }
    else
    {
        //add warning message to log
        //send email notification
    }
}

However, I don't like catching all exceptions like that (I know it's bad practice). What's the best way to go about this?
Are there particular exceptions I should be catching? Or, is this a good time to implement a using statement (if so can I have some help with how)?

A:

The exception could be lots of things - it might be just a timeout, or a 404 error, a 500 error, a connection reset error... so there's probably a bunch of exceptions that can be thrown. In this particular case I wouldn't have a problem with a global catch.
You might want to consider retries as well, if it fails the first time try again, in case it was just a timeout.
Alternatively if you already have global error handling on your app, you might not want to  swallow the exception, so you could just use the finally block without the catch:
try
{
    ....
}
finally
{
    ....
}

But you'd only want to do this if it was a genuine error that the app couldn't handle or resolve by itself.


Q:

Required / included once. Already defined notices

Not sure why this is happening.
Notice: Constant HOST already defined in con.php on line 11

Notice: Constant USER already defined in con.php on line 12

Notice: yardy yardy lalala etc

All the calls I make to con.php use require_once or include_once.
con.php consists of :
define("HOST", "x");
     define("USER", "x");
     define("PASSWORD", "x");
     define("DATABASE", "x");

Can anyone shed some light on this?

A:

The error message says it all. Those constants are defined elsewhere. One way to work around that is to check to see if they are defined and then only define them if they are not.
defined("HOST")            || define("HOST", "x");
defined("USER")            || define("USER", "x");
defined("PASSWORD")        || define("PASSWORD", "x");
defined(define("DATABASE") || define("DATABASE", "x");

The better solution would be to try to avoid including the files they are defined in more then once. But if you can't help it then the above method should solve your problem.


Q:

Make database operation and sending email a transaction

I have a website for booking hotels. After booking successfully, an email is gonna be sent to client. I did it as follow:
- Update table "booking"
- Check the result
   + If true, send email
   + Else return error

But what if the email isn't sent? That the DB was inserted but the email was not sent. It makes the booking operation isn't right. How to make DB operation and sending email transaction? Is there any easy way to do it? A and B must succeed or none of them.

A:

A transaction in the strict sense of the world can't stretch something inside the DB as well as soemthing outside the DB. So we have to redefine "transaction" to be, that either all actions fail, or all succeed.
Here is an idea:

Start DB transaction

Update table "booking"
Write an undo record into a table, with status "updated, not sent". This needs to have some ID, that can be used to undo the booking

Commit DB transaction
If this fails, bail out (no need to rollback)
Send the email
If this goes OK

Delete undo record
return "success"

else

Use undo record to undo the booking
Delete undo record
return "error"

There are 2 things to understand:

on an OS crash, Power out, etc. you have to manually check the undo table and compare it to the mailserver logs: The crash might have happend with the mail just failing, or with the mail being just sent, but not recorded
Most important: I have yet to see a quick mechanism, that reliably tells, whether an email has been sent or not. I mean really sent, not enqueed somewhere

A:

You could use database transactions, if you are using InnoDB:
Pseudo code:
Start DB transaction
Update table "booking"
Check the result
If true, send email
If email sends, commit your transaction
Else rollback your transaction, and return error

More info on transactions here: http://dev.mysql.com/doc/refman/5.0/en/commit.html


Q:

Assign a block to more than 1 region

How do I assign a block (the very same block) twice or thrice to different regions? The idea is not to have the same block on the same page more than once, but in different locations on different pages, so four 'displays' would be available:

Block X in the $top_left region
Block X in the $top_right region
Block X in the $above_content region
Block X hidden

Where it should be located, should be as simple as adding node paths in the textare, right? I understand that's what it's for...
If it's a module (please god no, not another module!), I'd like a few details.
Thanks.

A:

You'll want to look into the Context module, which will let you assign blocks based on sets of conditions. You create a context, set up a couple of conditions, then create a reaction to those conditions where your block appears.
So, let's say you wanted to show Block X on the front page and when a user is logged in. When it's the front page Block X is in Region 1, but when the user is logged in, Block X is in Region 2.
You'd create two contexts:

Conditions: Is Front Page, User is anonymous, Reactions: Show Block X in Region 1
Conditions: User is logged in, Reactions Show Block X in Region 2

I'm generalizing here, but you'll see what conditions and reactions are available for use when you install Context.


Q:

maven versions plugin: How to update parent to specific version, not latest?

Are there any ways to update parent to specific version using mvn?
I tried to use Versions plugin, but it updates to latest version.
E.g.:
I have parent versions 1.4 and 1.5.
I want child to use 1.4.
I tried:
mvn versions:update-parent

This updates parent version to 1.5 (latest).

A:

I am using it like this:
 mvn -f parent\pom.xml versions:set -DnewVersion=1.1.2-SNAPSHOT


Q:

Dynamically displaying, adding, and deleting attachments from email template before sending email

-> A custom link on the contacts page invokes a VF page
-> This VF page simulates the Send an Email page while auto populating a predefined email template:
<apex:page standardController="contact" extensions="custom_button_controller" id="ThePage">
    <apex:form id="theForm">
        <apex:pageBlock id="theBlock" mode="inlineEdit">
                <apex:outputLabel value="To  "/>
                <apex:outputField value="{!Contact.name}"/>

                <apex:outputLabel value="Cc  "/>
                <apex:inputtext value="{!Cc}"/>

                <apex:outputLabel value="Subject  "/>
                <apex:outputField value="{!emailTemp.subject}"/>

 Body

                <apex:inputTextarea value="{!emailTemp.HtmlValue}" richText="true" rows="25" cols="100"/>

                <apex:commandButton action="{!sendEmail}" value="Send Email" id="theButton"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

-> The apex code:
public class custom_button_controller {

            string contact_id{get;set;}
            public EmailTemplate emailTemp{get;set;}
            public string cc{get;set;}
            contact c;
            public custom_button_controller(ApexPages.StandardController controller) {
                   contact_id = apexpages.currentpage().getparameters().get('id');
                   c = [Select FirstName from contact where id=: contact_id];
                   emailTemp  = [select Subject, Name, Id, HtmlValue From EmailTemplate where id='00X50000001XtXB'];
            }
            public pagereference sendEmail(){
                    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                    //message.setTemplateId('00X50000001XtXB');
                    message.setTargetObjectId(contact_id);
                    List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

                    for (Attachment a : [select Name, Body, BodyLength from Attachment])
                    {
                      Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                      efa.setFileName(a.Name);
                      efa.setBody(a.Body);
                      fileAttachments.add(efa);
                    }
                    //message.setCcAddresses();
                    emailTemp.HtmlValue = emailTemp.HtmlValue.replace('{!Contact.FirstName}',c.FirstName);
                    message.setHtmlBody(emailTemp.HtmlValue);
                    message.setFileAttachments(fileAttachments);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{message});
                    return null;
                }

            }

What is working:

Neat editable preview of the HTML body on the VF page (except for merge field, explained below)
Sending email successfully with the right attachments
Successful inline editing of the email body, which results in an updated body sent

What is NOT working:

Email recipient sees merge field {!Contact.FirstName}, instead of the merge field value. Rather than reading Dear Diary, it's Dear {!Contact.FirstName},. This merge field (not its value) is also seen in the text area preview that the user can edit before sending out the email. Update: Got this working by using replace() to replace merge field with contact.firstname. See code
Adding cc address to the email. Tried setCcAddress() in the code. Need help adding this cc address before sending out the email
Displaying attachments as well as giving the user the option to add and delete attachments all on the same single 'Send an Email' VF page
When the send button is clicked, the page (browser tab) is closed and the user views the concerned contact record
Having the To field on the VF page as a lookup field to show emails of contacts and users

Appreciate your time.

A:

Update one more time : The code below can send email, add attachements, delete attachments on the fly and reload the same page to send more emails.
Page:
<apex:page standardController="contact" extensions="custom_button_controller" id="ThePage">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"/>
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js"/>
    <apex:form id="theForm">
        <apex:pageBlock id="theBlock" mode="inlineEdit">
                <apex:outputLabel value="To  "/>
                <apex:outputField value="{!Contact.name}"/>

                <apex:outputLabel value="Cc  "/>
                <apex:inputtext value="{!Cc}"/>

                <apex:outputLabel value="Subject  "/>
                <apex:outputField value="{!emailTemp.subject}"/>

 Body

                <apex:inputTextarea value="{!emailTemp.HtmlValue}" richText="true" rows="25" cols="100"/>

                <apex:commandButton action="{!sendEmail}" value="Send Email" id="theButton"/>
        </apex:pageBlock>

    <apex:pageblock title="Attachments">
    <apex:commandButton value="New Attachment" action="{!attach_new}"/>
    <apex:commandButton value="delete" action="{!getSelected}" />
        <apex:pageblocktable value="{!Selectedattachments}" var="a">
            <apex:column headerValue="Select to Delete ">
            <apex:inputCheckbox value="{!a.selected}" id="checkedone">

            </apex:inputCheckbox>
            </apex:column>
           <apex:column headerValue="Attachment Id"   value="{!a.acc.id}"/>
           <apex:column headervalue="Attachment Name" value="{!a.acc.name}"/>
        </apex:pageblocktable>

    </apex:pageblock>
    </apex:form>

</apex:page>

Controller :
 public class custom_button_controller {

            string contact_id{get;set;}
            public EmailTemplate emailTemp{get;set;}
            public string cc{get;set;}
            List<attachwrapper> attach= new List<attachwrapper>();
            list<attachment> selectedAttach = new list<attachment>();
            List<attachment> attach_criteria = new List<attachment>();

            public string Attach_to_delete_Id{get;set;}
            contact c;

            public List<string> cc_addresses{get;set;}
            public custom_button_controller(ApexPages.StandardController controller) {

                   contact_id = apexpages.currentpage().getparameters().get('id');
                   c = [Select FirstName from contact where id=: contact_id];
                   emailTemp  = [select Subject, Name, Id, HtmlValue From EmailTemplate limit 1];
                   cc_addresses = new List<string>();
            }

                public List<attachwrapper> getattach()
                {
                     attach.clear();
                     if(selectedattach.size() > 0){
                        attach_criteria =  [select id,name from attachment where Id NOT IN: selectedattach and parentId =: '00X50000001XtXB'];
                     }
                     else{
                     attach_criteria = [select id,name from attachment where ParentId =: '00X50000001XtXB'];
                     }

                    for(Attachment a :  attach_criteria ){
                    attach.add(new attachwrapper(a));}
                    return attach ;
                }
                public PageReference getSelected()
                {

                    selectedattach.clear();
                    for(attachwrapper awrapper : attach){
                    if(awrapper.selected == true){
                    selectedattach.add(awrapper.acc);}
                    }
                    return null;
                }
                public List<attachwrapper> GetSelectedattachments()
                {
                    if(selectedattach.size()>0){
                    return getattach();
                    }
                    return getattach();
                }

                public pagereference sendEmail(){
                    if(cc.length() >0 && cc != null){
                        List<string> split_cc = new List<string>();
                        split_cc = cc.split(';');
                        for(string s: split_cc){
                            cc_addresses .add(s);
                        }

                    }
                    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                    //message.setTemplateId('00X50000001XtXB');
                    message.setTargetObjectId(contact_id);
                    List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

                    for (Attachment a : [select id,name,body from attachment where id IN: attach_criteria])
                    {
                      Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                      efa.setFileName(a.Name);
                      efa.setBody(a.Body);
                      fileAttachments.add(efa);
                    }
                    message.setCcAddresses(cc_addresses );
                    emailTemp.HtmlValue = emailTemp.HtmlValue.replace('{!Contact.FirstName}',c.FirstName);
                    message.setHtmlBody(emailTemp.HtmlValue);
                    message.setFileAttachments(fileAttachments);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{message});
                    return null;
                }

                public pagereference attach_new(){
                pagereference pag = new pagereference('/apex/addattachments');
                pag.getParameters().put('contact_id', contact_id);
                return pag;
                }

            public class attachwrapper{
                public attachment acc{get; set;}
                public Boolean selected {get; set;}
                public attachwrapper(attachment a){
                    acc = a;
                    selected = false;
                }
            }
}

Page for adding new attachment
Page:
<apex:page controller="AttachmentUploadController">
  <apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>

  <apex:form enctype="multipart/form-data">
    <apex:pageMessages />
    <apex:pageBlock title="Upload a Attachment">

      <apex:pageBlockButtons >
        <apex:commandButton action="{!upload}" value="Save"/>
      </apex:pageBlockButtons>

      <apex:pageBlockSection showHeader="false" columns="2" id="block1">

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File Name" for="fileName"/>
          <apex:inputText value="{!attachment.name}" id="fileName"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!attachment.description}" id="description"/>
        </apex:pageBlockSectionItem>

      </apex:pageBlockSection>

    </apex:pageBlock>
  </apex:form>
</apex:page>

Controller:
public with sharing class AttachmentUploadController {
public string contact_Id{get;set;}
  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }

  public PageReference upload() {
    contact_Id = apexpages.currentpage().getparameters().get('contact_id');
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = contact_Id; // the record the file is attached to
    attachment.IsPrivate = true;

    try {
      insert attachment;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    } finally {
      attachment = new Attachment();
    }

    pagereference pag = new pagereference('apex/testing_emailK?id='+contact_id);
    pag.setredirect(true);
    return pag;
  }

}


Q:

Pandas update column with search string

Hello I am practicing with pandas and I am trying to figure out how to set the category field to Fees whenever there is a match of on "Fee".  I tried a masking technique that did not work.  Thanks
df = g1_2019[g1_2019['Description'].str.contains('Fee')]
df.head()

Index   Date    No. Description Category
495 3/18/2019   0   Withdrawal RW-ISA:Fee: International Service Fee    Not Categorized
496 3/18/2019   0   International Service Fee Assessed = $0.07 on ...   Not Categorized
650 4/17/2019   0   Withdrawal RW-ISA:Fee: International Service Fee    Not Categorized
651 4/17/2019   0   International Service Fee Assessed = $0.07 on ...   Not Categorized
879 5/17/2019   0   Withdrawal RW-ISA:Fee: International Service Fee    Not Categorized

A:

Try:
mask = g1_2019['Description'].str.contains('Fee')
g1_2019.loc[mask, "Category"] = "Fees"


Q:

On average, how long do Adventurers League sessions last?

On average, how long do sessions tend to last in Adventurers League organized play for D&D 5e?

A:

Average is difficult to pin down.
There's no good way to determine how long the "average" session is, because there's a great variety of content available. That said, the DDAL Content Catalog can provide some guidance on expected lengths. You could calculate an average based on all published content, but it wouldn't reflect popularity. Some content is simply better than other content, and as a consequence played and replayed more often.
Published Length
Modules range anywhere from five one-hour mini-modules, to two-hour, four-hour, and a small number of eight-hour modules. Season 8 added the concept of one-hour "bonus objectives" to both two-hour and four-hour modules, resulting in the possibility of any single module taking from one to eight hours.
Actual Length
I've been running and playing DDAL for many years now in game stores, at home, and at conventions. Over that time, I've come to the conclusion that the published module length is generally off by about 50% if you want to give the full, unrushed experience: two-hour modules take three, four-hour modules take six, and so on.
This is problematic in a game store or convention where the time is limited. You either have to split up the module (and hope you get all the same players for the second part), cut down the module to squeeze it into the allotted time (giving an inferior experience), or drastically curtail roleplaying and characterization (no fun in my book).
Hardcover adventures can take many, many hours - sometimes over a hundred (I recently completed playing Dungeon of the Mad Mage over 36 sessions at four hours each). While they can be done in a game store with a rotating cast, they're best done with a fixed cast - trying to rush or squeeze a hardcover adventure is highly detrimental to the storytelling.


Q:

Irreducible factors of a polynomial in a Galois extension

Let $E|F$ be a finite Galois extension and $f(x) \in F[x]$ an irreducible polynomial. Prove that each of the irreducible factors of $f(x)$ in $E[x]$ have the same degree.
An idea: Let $\phi \in Gal(E|F)$ and $f(x)=g_1(x) \ldots g_m(x)$, where $g_i(x) \in E[x]$ is irreducible. Since $\phi$ fixes F, $f(x)=\phi f(x)=\phi g_1(x) \ldots \phi g_m(x)$. Therefore, since factorization is unique $\phi$ permutes the $g_i$'s. Note that $\phi$ preserves the polynomial's degree. So, if we can show that $Gal(E|F)$ acts transitively on $\{g_1(x), \ldots ,g_m(x)\}$, then we are done.

A:

Let $g_1(x)$ be one of the irreducible factors in $E[x]$. Let $H\le G$ be the subgroup of automorphisms that fixes all the coefficients of $g_1$, and let $D=\{\tau_1,\tau_2,\ldots,\tau_k\}$ be a set of representatives of left cosets of $H$.
Consider the polynomial
$$
g(x)=\prod_{i=1}^k(\tau_i g_1)(x).
$$
Fix an element $\phi\in G$. We have that $\phi D$ is another set of reprensentatives of left cosets of $H$. In other words there is a permutation $\alpha\in S_k$ such that
$$
\phi\tau_i=\tau_{\alpha(i)}h_i
$$
for all $i=1,2,\ldots,k,$ and some elements $h_i\in H$. Therefore
$$
\begin{aligned}
(\phi g)(x)&=\prod_{i=1}^k(\phi\tau_i g_1)(x)\\
&=\prod_{i=1}^k(\tau_{\alpha(i)}h_i g_1)(x)\\
&=\prod_{i=1}^k(\tau_{\alpha(i)}g_1)(x)\\
&=g(x).
\end{aligned}
$$
As $\phi$ was arbitrary this means that $g(x)$ is fixed under all of $G$. Therefore $g(x)\in F[x]$.
As you observed, all the polynomials $\tau_i g_1$ are factors of $f$. As they are distinct, so is their product $g(x)$. But $f(x)$ was assumed to be irreducible, so we must have $g(x)=f(x)$. The claim follows from this the way you outlined.


Q:

Display image while dragging

How can i put an image in corner or center of cursor while user dragging an item in ListView or other controls like that?
When you dragging an image or text in Firefox; same thing occurs.

A:

The most effective way I've found is to use the Adorner Layer.
This post shows how: http://blogs.msdn.com/b/marcelolr/archive/2006/03/03/showing-drag-drop-feedback-on-the-wpf-adorner-layer.aspx


Q:

NSMutableData appendData with NSArray data

To append a simple string key-value pair, we do this in object C
   NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\n\r\n%@", _name, _value] dataUsingEncoding:NSUTF8StringEncoding]];

However, how do we append  NSArray of data.  Let's say Email Array contains={tom@yahoo.com, dve@yahoo.com, john@yahoo.com}
How do we append Email array to the NSMutableData body?

A:

you can turn your array into NSString as you did with single string:
NSArray array = [[NSArray alloc] init];
...
[body appendData:[[NSString stringWithFormat:@"%@", array] dataUsingEncoding:NSUTF8StringEncoding]];

but I recommend to use NSKeyedArchiver, see this topic


Q:

changingThisBreaksApplicationSecurity angular2

I am trying to load a pdf document in an  tag in angular2 Dynamically, and when I am trying to change the URL iths throwing an error saying

SafeResourceUrlImplchangingThisBreaksApplicationSecurity:
  "localhost:8002/pdf.pdf"proto:
  SafeValueImplconstructor:
  SafeResourceUrlImpl()getTypeName: ()proto: Object
localhost:8002/pdf.pdf Failed to load resource:
  net::ERR_UNKNOWN_URL_SCHEME

Here's how I am setting the URL,
This method will be called when I need to show the component
public show(): void {
    this.visible = true;
    this.visibleAnimate = true;
    console.log(this.src)
    this.DocURL = this.sanitizer.bypassSecurityTrustResourceUrl(this.src);
    console.log(this.DocURL);
}

constructor(private sanitizer: DomSanitizer) {
    this.visible = false;
    this.visibleAnimate = false;

    this.DocURL = this.sanitizer.bypassSecurityTrustResourceUrl(window.location.host + "/pdf.pdf");
}

Heres the HTML Part

    <object width="870" height="650" type="application/pdf" [data]="DocURL" id="doc" #doc>

Not able to display the document

    </object>

The URL I am supplying will be dynamic

A:

Your URL does not have a protocol. Try the following:
this.DocURL = this.sanitizer.bypassSecurityTrustResourceUrl(window.location.protocol + '//' + window.location.host + "/pdf.pdf");


Q:

(#100) "Subject should be a page account" error when trying to publish video to facebook page

I'm trying to make an application that able to publish video to a Facebook page. I obtain list of available pages via /me/account request and get correct response:
[{
  "access_token":"XXX",
  "category":"Music Video",
  "category_list":[{"id":"1207","name":"Music Video"}],
  "name":"My mighty musical page",
  "id":"XXX",
  "tasks":["ANALYZE","ADVERTISE","MODERATE","CREATE_CONTENT","MANAGE"]
}]

after this I take the "id" value and send request to start live video, using the id value as page-id in the link:

{Request:  accessToken:
      {AccessToken token:ACCESS_TOKEN_REMOVED permissions:[manage_pages, publish_video, publish_pages, user_videos, public_profile,
  pages_show_list, publish_to_groups, groups_access_member_info,
  email]},
      graphPath: /XXX/live_videos,
      graphObject: null,
      httpMethod: POST,
      parameters: Bundle[{privacy={"value":"EVERYONE"}}]
      }

As a result I receive the following error:

{HttpStatus: 400, errorCode: 100, subErrorCode: -1, errorType:
  OAuthException, errorMessage: (#100) Subject should be a page account}
  /APP: [FacebookFramework] Attempt to start streaming to
  Facebook returned the error: code 100, message: (#100) Subject should
  be a page account
      {FacebookServiceException: httpResponseCode: 400, facebookErrorCode: 100, facebookErrorType: OAuthException, message:
  (#100) Subject should be a page account}

that actually describes nothing about what goes wrong. I have all required permissions. I am creator of the page and have admin rights. I have no idea where can I find this "correct id". Did I miss something important?
PS. Also I use similar code to post to a group and it works ok.

A:

Yes, you were right, the problem was that I did not pass correct token when tried to start streaming. Correct token is received with /me/account response. I created token the following way
        final AccessToken currentToken = getCurrentAccessToken();
        new AccessToken (
            "XXX", //custom token string here
            currentToken.getApplicationId(),
            currentToken.getUserId(),
            currentToken.getPermissions(),
            currentToken.getDeclinedPermissions(),
            null,
            null,
            null,
            null
        );

and it works well with this new token


Q:

gnatbind: Cannot find: s-stalib.ali

I installed GNAT on my OS X 10.8.5 machine with the following steps:

Download GNAT GPL from http://libre.adacore.com/download/configurations
Install with ./doinstall, accepting all the default options
Added /usr/local/gnat/bin to $PATH

After trying to compile a simple hello world example I get this error:
$ gnat make hello
gcc -c hello.adb
gnatbind -x hello.ali
gnatbind: Cannot find: s-stalib.ali
gnatmake: *** bind failed.

Any idea why this might happen?
PS: gnat make -a hello works, but creates tons of files and should not be required as far as i know.
Edit: As requested, here is the output of gnatls -v
GNATLS GPL 2013 (20130314)
Copyright (C) 1997-2013, Free Software Foundation, Inc.

Source Search Path:
   <Current_Directory>
   /usr/local/gnat/lib/gcc/x86_64-apple-darwin12.2.0/4.7.4/adainclude/

Object Search Path:
   <Current_Directory>
   /usr/local/gnat/lib/gcc/x86_64-apple-darwin12.2.0/4.7.4/adalib/

Project Search Path:
   <Current_Directory>
   /usr/local/gnat/x86_64-apple-darwin12.2.0/lib/gnat
   /usr/local/gnat/share/gpr
   /usr/local/gnat/lib/gnat

Here's an excerpt of the output of ls -l /usr/local/gnat/lib/gcc/x86_64-apple-darwin12.2.0/4.7.4/adalib/:
total 39224
-rw-rwxr--@ 1 padde  admin     4483 17 Apr  2013 Makefile.adalib
-rw-rwxr--@ 1 padde  admin     1450  3 Jun 18:00 a-assert.ali

...

-rw-rwxr--@ 1 padde  admin     3178  3 Jun 18:01 s-rpc.ali
-rw-rwxr--@ 1 padde  admin     3778  3 Jun 18:01 s-scaval.ali
-rw-rwxr--@ 1 padde  admin     4908  3 Jun 18:01 s-sequio.ali
-rw-rwxr--@ 1 padde  admin    10542  3 Jun 18:01 s-shasto.ali
-rw-rwxr--@ 1 padde  admin     6382  3 Jun 18:01 s-solita.ali
-rw-rwxr--@ 1 padde  admin     8265  3 Jun 18:01 s-stausa.ali
-rw-rwxr--@ 1 padde  admin     4919  3 Jun 18:01 s-stchop.ali
-rw-rwxr--@ 1 padde  admin    14601  3 Jun 18:01 s-stratt.ali
-rw-rwxr--@ 1 padde  admin    11024  3 Jun 18:01 s-ststop.ali
-rw-rwxr--@ 1 padde  admin     5320  3 Jun 18:01 s-stusta.ali
-rw-rwxr--@ 1 padde  admin     9804  3 Jun 18:01 s-taasde.ali
-rw-rwxr--@ 1 padde  admin     4346  3 Jun 18:01 s-tadeca.ali
-rw-rwxr--@ 1 padde  admin     4234  3 Jun 18:01 s-tadert.ali
-rw-rwxr--@ 1 padde  admin    12564  3 Jun 18:01 s-taenca.ali
-rw-rwxr--@ 1 padde  admin     6663  3 Jun 18:01 s-taprob.ali
-rw-rwxr--@ 1 padde  admin    29033  3 Jun 18:01 s-taprop.ali
-rw-rwxr--@ 1 padde  admin    13719  3 Jun 18:01 s-tarest.ali
-rw-rwxr--@ 1 padde  admin     8863  3 Jun 18:01 s-tasdeb.ali
-rw-rwxr--@ 1 padde  admin      747  3 Jun 18:01 s-tasinf.ali
-rw-rwxr--@ 1 padde  admin    13008  3 Jun 18:01 s-tasini.ali
-rw-rwxr--@ 1 padde  admin    15237  3 Jun 18:01 s-taskin.ali
-rw-rwxr--@ 1 padde  admin     1259  3 Jun 18:01 s-tasloc.ali
-rw-rwxr--@ 1 padde  admin     1710  3 Jun 18:01 s-taspri.ali
-rw-rwxr--@ 1 padde  admin    11652  3 Jun 18:01 s-tasque.ali
-rw-rwxr--@ 1 padde  admin    29450  3 Jun 18:01 s-tasren.ali
-rw-rwxr--@ 1 padde  admin     1500  3 Jun 18:01 s-tasres.ali
-rw-rwxr--@ 1 padde  admin    31332  3 Jun 18:01 s-tassta.ali
-rw-rwxr--@ 1 padde  admin    11059  3 Jun 18:01 s-tasuti.ali
-rw-rwxr--@ 1 padde  admin     7120  3 Jun 18:01 s-tataat.ali
-rw-rwxr--@ 1 padde  admin     2942  3 Jun 18:01 s-tpinop.ali
-rw-rwxr--@ 1 padde  admin    11318  3 Jun 18:01 s-tpoben.ali
-rw-rwxr--@ 1 padde  admin    19570  3 Jun 18:01 s-tpobop.ali
-rw-rwxr--@ 1 padde  admin    11075  3 Jun 18:01 s-tposen.ali
-rw-rwxr--@ 1 padde  admin     1421  3 Jun 18:01 s-traces.ali
-rw-rwxr--@ 1 padde  admin     3889  3 Jun 18:01 s-tratas.ali
-rw-rwxr--@ 1 padde  admin    17789  3 Jun 18:01 s-utf_32.ali
-rw-rwxr--@ 1 padde  admin     8312  3 Jun 18:01 s-vaflop.ali
-rw-rwxr--@ 1 padde  admin      997  3 Jun 18:01 s-valboo.ali
-rw-rwxr--@ 1 padde  admin     1239  3 Jun 18:01 s-valcha.ali
-rw-rwxr--@ 1 padde  admin     1309  3 Jun 18:01 s-valdec.ali
-rw-rwxr--@ 1 padde  admin     2921  3 Jun 18:01 s-valenu.ali
-rw-rwxr--@ 1 padde  admin     1733  3 Jun 18:01 s-valint.ali
-rw-rwxr--@ 1 padde  admin     1345  3 Jun 18:01 s-vallld.ali
-rw-rwxr--@ 1 padde  admin     1807  3 Jun 18:01 s-vallli.ali
-rw-rwxr--@ 1 padde  admin     3841  3 Jun 18:01 s-valrea.ali
-rw-rwxr--@ 1 padde  admin     3078  3 Jun 18:01 s-valuns.ali
-rw-rwxr--@ 1 padde  admin     2863  3 Jun 18:01 s-valwch.ali
-rw-rwxr--@ 1 padde  admin     2157  3 Jun 18:01 s-veboop.ali
-rw-rwxr--@ 1 padde  admin      535  3 Jun 18:01 s-vector.ali
-rw-rwxr--@ 1 padde  admin     1153  3 Jun 18:01 s-vercon.ali
-rw-rwxr--@ 1 padde  admin     3305  3 Jun 18:01 s-vmexta.ali
-rw-rwxr--@ 1 padde  admin     2474  3 Jun 18:01 s-wchwts.ali
-rw-rwxr--@ 1 padde  admin      698  3 Jun 18:01 s-widboo.ali
-rw-rwxr--@ 1 padde  admin      939  3 Jun 18:01 s-widcha.ali
-rw-rwxr--@ 1 padde  admin     2526  3 Jun 18:01 s-widenu.ali
-rw-rwxr--@ 1 padde  admin      863  3 Jun 18:01 s-widlli.ali
-rw-rwxr--@ 1 padde  admin     1126  3 Jun 18:01 s-widllu.ali
-rw-rwxr--@ 1 padde  admin     1292  3 Jun 18:01 s-widwch.ali
-rw-rwxr--@ 1 padde  admin     1301  3 Jun 18:01 s-wwdcha.ali
-rw-rwxr--@ 1 padde  admin     5682  3 Jun 18:01 s-wwdenu.ali
-rw-rwxr--@ 1 padde  admin     1957  3 Jun 18:01 s-wwdwch.ali
-rw-rwxr--@ 1 padde  admin     1561  3 Jun 18:01 sequenio.ali
-rw-rwxr--@ 1 padde  admin     1519  3 Jun 18:01 text_io.ali
-rw-rwxr--@ 1 padde  admin      391  3 Jun 18:01 unchconv.ali
-rw-rwxr--@ 1 padde  admin      389  3 Jun 18:01 unchdeal.ali

Interestingly, the requested file s-stalib.ali is not contained in this directory.

A:

If you say gnatls -v (or gnat list -v), it lists (amongst other things) the object search path: here,
...
Object Search Path:
   <Current_Directory>
   /opt/gnat-gpl-2013/lib/gcc/x86_64-apple-darwin12.2.0/4.7.4/adalib/
...

What does yours say? is it right? if the files are there, are they readable?
[Later]
OK, you have 9 s-s*.ali files, with protection -rw-rwxr--@ (I'm not sure what the @ means!), whereas I have 19, with protection -r--r--r--@. This looks as though the installation didn't complete for some reason.
When I install GNAT, I use sudo: sudo ./doinstall. Could that be the difference?
The README says that doinstall leaves install.log in the current (distribution, I suppose) directory; that might give some clues.
If you do decide to rebuild the library, it's be best to use Makefile.adalib in the "installed" adalib/ directory.
Good luck!


Q:

Update data in ngDialog

I am using ngDialog in my project with data from my scope. I have a scope object named popupConge that I link to data of ngDialog :
ngDialog.open({
        template: 'saisieCongeModalPanel',
        className: 'ngdialog-theme-default width800',
        data: $scope.popupConge,
        scope: $scope,
    });

The problem is that when I update $scope.popupConge, the data in my modal panel aren't updated.
For instance I have: <input type="text" id="motif" ng-model="ngDialogData.conge.motif"/> in my ngDialog. When I update $scope.popupConge.conge.motif, the input field isn't updated :s
Did I do something wrong ?
Thanks !

A:

Since you are passing $scope to the dialog you should use the popupConge.conge.motif instead.
Try this.
<input type="text" id="motif" ng-model="popupConge.conge.motif"/>