Q:

Entity Framework Model-First Enum Type MetadataType

I know when working with model-first development, you can use partial classes generated by the t4 templates to add metadata. e.g.
public partial class Address
{
    public int Id { get; set; }
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

Then in a separate file, I do:
[MetadataType(typeof(AddressMetadata))]
public partial class Address {
}

internal sealed class AddressMetadata {

    [Display(Name = "Street")]
    public string Street1 { get; set; }

    [Display(Name = "Street (cont.)")]
    public string Street2 { get; set; }

    [Display(Name = "Zip code")]
    public string Zip { get; set; }
}

I'm trying to do this for an enum type defined within the EDMX file.
// this doesn't work
[MetadataType(typeof(ContactTypeMetadata))]
public enum ContactType {

}

public class ContactTypeMetadata {
}

Doing this, I get the following error:
Error   1   The namespace 'Models' already contains a definition for 'ContactType'

Is there anyway to do the same functionality for the enumerations as you can do for the classes in a model-first project?
EDIT
Within the EDMX file, I've defined an enum type:
namespace WindowsFormsApplication1
{
    using System;

    public enum ContactType : int
    {
        CEO = 0,
        CIO = 1,
        Peasant = 2
    }
}

I'm trying to find a way using a similar mechanism (in separate files so that if I modify the EDMX my changes won't get overwritten) to accomplish this:
namespace WindowsFormsApplication1
{
    using System;

    public enum ContactType : int
    {
        [Display(Name="Chief Executive Officer")]
        CEO = 0,

        [Display(Name="Chief Information Officer")]
        CIO = 1,

        [Display(Name="Regular Employee")]
        Peasant = 2
    }
}

A:

You need to disable code generation for your enum. You can do this by referencing an external type.
Create an enum outside of your .edmx. E.g.
ContactType.cs in the root of your project, although you can place it wherever you like so long as you know what namespace it is in.
Copy out your current code from the edmx enum you already created and paste it into your newly created ContactType.cs file, as shown below.
ContactType
using System;
namespace YourEnumNamespace
{
    public enum ContactType : int
    {
        [Display(Name="Chief Executive Officer")]
        CEO = 0,

        [Display(Name="Chief Information Officer")]
        CIO = 1,

        [Display(Name="Regular Employee")]
        Peasant = 2
    }
}

Now in your .edmx Model delete your existing ContactType enum, this is located in the Model Browser under the Enum Types section, simply select it and delete it.

Go back to your Solution Browse, open your edmx and right click somewhere and click 'Add New' and then 'Enum Type'.

Finally name your enum type ContactType and tick Reference External type, here fully qualify your custom enum you created as I showed earlier. E.g. YourEnumNamespace.ContactType.
This tells the edmx to use an external enum and not generate the enum code within the edmx itself.

Finally within the entity within your edmx file that you wish to use your custom enum with, select the property that you want to use with your custom enum, in this case I've called it MyContactTypeProperty

And change the property type to your custom enum.

And there you go. No need to frig around trying to declare partial enums and the like, for the record you can't have a partial enum. Anyway this will do what you need. Good luck!


Q:

How to store a line from a textfile into an array of fixed size

So, I have this scenario where I am reading from a file which has a structure like this:
4
4 8 2 1
2 4 6 3
3 6 9 2
1 3 2 8

Where 4 in the first line is the size of the matrix that will be generated.
The lines below are the matrix values which will always be a multi dimensional matrix of size [4,4] means that it will have 4 rows and 4 columns.
How can I store in this in a data structure and access the elements for performing calculations?
My current code:
class Program
{
    static void Main(string[] args)
    {
        var fileName = "sampleinput.txt";
        int T = Convert.ToInt32(File.ReadLines(fileName).First()); // gets the first line from file.
        var lines = File.ReadLines(fileName).Skip(1).Take(T);
        int[,] array1 = new int[T, T];
        foreach(var line in lines)
        {

            Console.WriteLine(line);
            //How to store the values here in a multidimensional array and access the values as required?
        }

    }
}

A:

Try this out:
class Program
{
static void Main(string[] args)
{
    var fileName = "sampleinput.txt";
    int T = Convert.ToInt32(File.ReadLines(fileName).First()); // gets the first line
     from file.
    var lines = File.ReadLines(fileName).Skip(1).Take(T);
    int[,] array1 = new int[T, T];
    var n = 0
    foreach(var line in lines)
    {
        var j = 0;
       foreach(var i in line.Split().Select(s => int.Parse(s)))
       {
        array1 [n, j] = i;
        j++;
       }
      n++;
    }

}
}


Q:

Missing noun in sentence using ほど

動物王国のムツゴロウさんちの娘になってもいいと思うほど、動物好きなまる子だが、...
  Maruko is a fan of animals to the extent that she thinks it's okay to become the daughter of something to do with animal kingdoms and mud skippers

Whilst I'm fascinated to know what 動物王国のムツゴロウさんち is all about, my primary question is about the structure of the sentence.
There seems to be a noun missing. If I had tried to put this in Japanese I would have written:

...ほど、まる子は動物がすきだが...
  to the extent that ... Maruko likes animals

But the original sentence is

to the extent that ... Maruko (who is an animal fan) is xxx?

where xxx is missing.
Is my alternative sentence correct? How can I understand the grammar of the original sentence?

A:

First of all, who is 「動物王国{どうぶつおうこく}のムツゴロウさん」?  He is a very well-known and highly popular figure in Japan.  When the older half of the country hear the word "animals", they think of him.  I will just let Wiki explain below.  It even talks about what his 「動物王国」 is about.
https://en.wikipedia.org/wiki/Masanori_Hata
Next, just a brief explanation of 「動物好{どうぶつず}きなまる子」.  For those unfamiliar, the 「好き」 part in this phrase, is read 「ずき」 and not 「すき」.
For reading comprehension, I recommend that one regard 「動物好きな」 as just an adjective meaning "animal-loving".  So, we have a "animal-loving Maruko" here.
I think many are already familiar with this, but 「～～さんち」 means "~~'s home", "~~'s family", etc.  The 「ち」 comes from 「うち」.
Now, you called 「動物王国のムツゴロウさんちの娘になってもいいと思うほど、動物好きなまる子だが、...」 a sentence, but is it one?  Grammatically, no, because it lacks a predicate.  If the author actually ended this with the "...", however, then it is an "honorary" sentence.  To make it as literal as possible, it means:

"It is Maruko who loves animals to the extent that she would not mind becoming the daughter of Mr. Mutsugoro of the Animal Kingdom."

The TL might sound awkward because I translated, as I said, a non-sentence that does not even have a predicate.
Even a one-step more literal translation would be:

"Maruko who loves animals so much that she would not mind becoming the daughter of Mr. Mutsugoro of the Animal Kingdom, but ......"

There you could see what I mean by "non-sentence" and "no predicate".  It says nothing about what Maruko actually did.
In any case, you seem to have a good grip on the phrase in question.  It is a good sign that you felt something was missing.


Q:

RxJs - Convert Flickr request to stream of photos

I'm a RXJS newbie.
Trying to figure out why this code doesn't work.
var $sources = $('#clickme');

var flickrApi = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=af11a8fa73ca2894e2f7c46ecd7a5a87&text=puppies&per_page=5&format=json&nojsoncallback=1";

Rx.Observable.fromEvent($sources, 'click')
.flatMap(click => Rx.Observable.fromPromise($.getJSON(flickrApi)))
.flatMap(response => Rx.Observable.fromArray(response.photos))
.subscribe(photo => console.log("The photo Object", photo));

The object is to run this flickr api, receive the photos and create a stream of single photo events.
For some reason subscribe doesn't happen.
Live (non-working) demo here: http://jsbin.com/pesiqo/2/edit
Thanks!

A:

Your code is not valid JavaScript (JavaScript does not have lambdas).
You should also supply an error handler to your subscribe call to catch any runtime errors that occur.  And you should check the response from Flickr to see if the request succeeded.
Just changing your code to valid JavaScript and it runs just fine, though it fails due to an invalid flickr API key.
var $sources = $('#clickme');

var flickrApi = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=af11a8fa73ca2894e2f7c46ecd7a5a87&text=puppies&per_page=5&format=json&nojsoncallback=1";

Rx.Observable.fromEvent($sources, 'click')
.flatMap(function (click) {
  return Rx.Observable.fromPromise($.getJSON(flickrApi));
})
.flatMap(function (response) {
  if (response.stat === "fail") {
    return Rx.Observable.throw(new Error(response.message));
  }
  return Rx.Observable.fromArray(response.photos);
})
.subscribe(function (photo) {
  console.log("The photo Object", photo);
}, function (error) {
  console.log("an error occurred", error, error.message, error.stack);
});

jsbin: http://jsbin.com/tupowacila/3/edit


Q:

How to Stack Overflow?

Many new users find it difficult to Stack Overflow. They make the same mistakes over and over, like asking unclear questions, no MCVE, too broad or use answers to comment.
I know that's our fault, but what if you can create a simple course to teach people how to Stack Overflow properly? We are not killing the site, we just don't know how to ask. And meta posts are boring. We need an interactive course (teacher: >1k rep users). Users will write the question and the teacher will teach how to improve the quality of the question. The course will also teach basic Stack Overflow things like how to logout, Markdown, be nice, interact with SOCVR bots... (that's too much, let's improve the questions first and then we will teach other things later). What do you think?

A:

Kate Gregory has created an extensive pluralsite course title Using Stack Overflow and Other StackExchange Sites. I highly recommend pointing new users at this material. It has topics covering:

Searching
Asking your first question
Managing your question
"When things don't go smoothly"
Answering Questions
Voting, Reputation, Privileges, and Other Features
Helping moderate

It is important to note that pluralsite is not free, but they do offer a free trial (10 days or 200 minutes of material, whichever is lower).

Regarding your suggested topics, I have a few comments:

logout

I don't think having a "course" for how to log out is a useful way to spend our time. It is literally two mouse clicks to get to the log out button.

Markdown

Markdown can be tricky, especially if you haven't used it previously. However, Stack Exchange provides a nice editor to handle most markdown automatically. They also provide a help link and a link to mark down specific help in the editor. If users aren't using links that are already right in their browser window, I don't know if directing them to another location for help will do much.

be nice

This isn't something that needs to be taught. However, I just walked through the new user sign up and didn't see a prominent link to "Be Nice" (or even get redirected to the Tour...instead, I was presented with Developer Story signup). Perhaps an easier thing to do would be to present this information to the user at sign up.

interact with SOCVR bots

This is not a new user "thing". New users need to know how to ask questions, answer questions, edit questions, up vote, and down vote. Interacting with bots in a moderation specific room, isn't a new user's goal.

A:

What do you think?

Yes, I agree that many users find it difficult to ask good questions on Stack Overflow, and I even think that some of them make the same mistakes several times.
I also agree that this is rather not Stack Overflow's fault, because there is plenty of information available that guides you through the process and in principle tells you everything you need to know in order to ask good questions. Just read a bit in the help center.
This may not be killing the site, but surely it seriously hurts it. Do you know how much effort it is to pay attention to, downvote and close bad questions? And all this while searching for the few really good questions that can and should be answered.
An interactive course for teaching how to use Stack Overflow might actually help with this, but I see two major problems with it:

There may not be enough users volunteering to teach.
Users who have a habit of posing bad question may not want to take the course.

That's why likely this idea won't go very far. But you are free to try it out. You could start by fleshing the idea out more (how should users know of this idea, where should the course take place, what should teachers do) and asking for voluntary teachers here on Meta (which isn't boring by the way).


Q:

Adding Syntax Highlighting to a Text Editor with Python

I am creating my own web-based text editor and I want to add in syntax highlighting. To start off I will on do highlighting for one language (Python, most likely), but later on I want to add highlighting for every language I can think of.
I would like to find a tutorial on this if possible, does anyone know of a place where I can find one
Also, if there are any other tips you can give me, that would be great.

A:

Take a look at Pygments.

highlight.js


Q:

How to append a string to each element of a Bash array?

I have an array in Bash, each element is a string. How can I append another string to each element? In Java, the code is something like:
for (int i=0; i<array.length; i++)
{
    array[i].append("content");
}

A:

You can append a string to every array item even without looping in Bash!
# cf. http://codesnippets.joyent.com/posts/show/1826
array=(a b c d e)
array=( "${array[@]/%/_content}" )
printf '%s\n' "${array[@]}"

A:

As mentioned by hal
  array=( "${array[@]/%/_content}" )

will append the '_content' string to each element.
  array=( "${array[@]/#/prefix_}" )

will prepend 'prefix_' string to each element

A:

Tested, and it works:
array=(a b c d e)
cnt=${#array[@]}
for ((i=0;i<cnt;i++)); do
    array[i]="${array[i]}$i"
    echo "${array[i]}"
done

produces:
a0
b1
c2
d3
e4

EDIT: declaration of the array could be shortened to
array=({a..e})

To help you understand arrays and their syntax in bash the reference is a good start. Also I recommend you bash-hackers explanation.


Q:

MySQL, Aggregate SubSelect Problem

I'm in the process of developing a site that will allow players of a certain game to upload their levels and tag them. Each player's account is actually an account in the forums that the site is using (SMF).
I am able to return all tags associated with a particular level no problems; I run into an issue when I want to filter those matching on the result of that subselect. It claims the column 'taglist' doesn't exist...
SELECT smf_members.realName,game_levels.*,
       (SELECT GROUP_CONCAT(tag)
          FROM `game_tags`
         WHERE `game_tags`.uuid = `game_levels`.uuid) AS taglist
  FROM `game_levels`
INNER JOIN `smf_members` ON `smf_members`.ID_MEMBER = `game_levels`.ID_MEMBER
WHERE taglist LIKE 'untagged'
ORDER BY `ID_TOPIC` DESC

Thanks in advance. I have also tried doing a second INNER JOIN on the tags table, narrowing the results by using a regular WHERE on game_tags.tag, but then I end up with a single row that has all the tags concatenated.

A:

You can't reference a column alias in the WHERE clause - the earliest MySQL supports column alias referencing is the GROUP BY.  Use:
  SELECT sm.realName,
         gl.*,
         x.taglist
    FROM GAME_LEVELS gl
    JOIN SMF_MEMBERS sm ON sm.id_member = gl.id_member
    JOIN (SELECT gt.uuid,
                 GROUP_CONCAT(gt.tag) AS taglist
            FROM GAME_TAGS gt
        GROUP BY gt.uuid) x ON x.uuid = gl.uuid
   WHERE x.taglist LIKE 'untagged'
ORDER BY ID_TOPIC DESC


Q:

How to DROP DATABASE named "/"

There is this database created automatically with a CMS. the database name is "/" without quotes. and when trying do delete it, this shows up.
mysql> DROP DATABASE /;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/' at line 1

mysql  Ver 14.14 Distrib 5.6.24, for debian-linux-gnu (x86_64) using  EditLine wrapper
Thank you for your help.

A:

You need backticks:
DROP DATABASE `/`;


Q:

Creating a SQL Login and User on an AlwaysOn Replica

I have a database (DB1) which is synced to (DB2) on another server (via AlwaysOn - SQL Server 2014).
I want to give a user read access to DB2. I create a SQL login and database user in DB1. The new database user is migrated to DB2, but the SQL login is not (which makes sense).
The problem is that when I attempt to create a SQL login for the user on DB2 and give the user read rights to DB2, tied to the user account that came from DB1, I get an error saying DB2 is read only and cannot be modified.
So, how can I accomplish this?

A:

You need to create the login on the DB2 server. Use Robert's script so that it grabs the sid and password, well if it's a SQL account that is.
Then grant the permission on DB1. That permission will auto-magically get copied over to DB2 due to the AG.
There is no way to just grant permission on DB2. It has to be done on DB1. You can control access by disabling the login on DB1 though.


Q:

Discovery of Chromecast devices using Android MediaRouter APIs

Discovery of Chromecast devices using Android MediaRouter APIs is not working as expected with latest mediarouter support library (version 19) and google play services version 4.2.43.
I'm using Cast Hello Text sample app for this issue. It can be found here: https://github.com/googlecast/CastHelloText-android.
I have my chromecast device plugged into the TV and in the same network as the Android device (Sender).

The app comes up and finds the Chromecast device. I override some of the relevant MediaRouter.Callback methods, so I see the onRouteAdded() being called.
Later, I unplug the device from my TV. I expect to get a onRouteRemoved() event. But this never happens.
The app still displays the cast icon. On selecting the device from the cast icon, the app attempts to connect to the device and fails. Now I get onRouteUnSelected() and onRouteRemoved() events and the cast icon disappears.
On plugging back the device to my TV and once the device is displaying the home screen, I expect to get a onRouteAdded() event. I do not get this event even after waiting for a few minutes.

This was working as expected in mediarouter library version 17 and with the preview google cast SDK.
So has something changed in terms of when these events are fired?
what is the right way to find out when a chromecast device is added and when it is removed? I plan on using a custom UI with MediaRouter APIs to display the cast icon and the device list.

A:

There is a bug in the latest version of Android SDK/Play services that causes the behavior you are seeing. This will be fixed in the next release of SDK and Google Play services.


Q:

OLD School asp.net page is taking large amount of time to complete the submit

We are running into a IE9 issue with old asp.net (VB) page and we are not sure what is happening and we are hoping someone can make some suggestions here

We have this .aspx page with pretty light controls and a button with a runat server
<div class="TopMargin">
    <button id="btnAddTemplate" runat="server"><asp:Image ID="imgAddTemplate"  SkinID="add" Height="12" Width="12" runat="server" /> Add New Template</button>
</div>

The Submit trigger a post back and we have a serverclick event attached to the button which just does a response .redirect
Between The Click and the Hitting the Page_Load in the code behind the page is getting stuck somewhere and it takes almost 90 sec to reach to page load from The Form submit on post back..
This happens only on IE9 and IE10 Chrome and firefox are fine.
Any Suggestions?

A:

Well got a solution but not sure why the other one is not working. if someone can help in explaining it that will be great
Replaced the
<button id="abc" runat="server"><asp:Image ID="imgAddTemplate"  SkinID="add" Height="12" Width="12" runat="server" /> Add New Template</button>

with the input type Button as
<input type="button" id ="abc" value="Add New Template" runat="server" />


Q:

ng-bind not showing anything after API call sets data

This is my code, and the username is not showing up in my DOM.
After the soundcloud API is initiated, the data is loading using a SC.get call, the callback function within sets the $scope.user to the response.
If i check my browser nothing will show up, any ideas solving this?

function trackCtrl($scope)
{
    $scope.initialize = function() {
        console.log('initialize');
        SC.initialize({
            client_id: "CLIENT_ID",
            redirect_uri: "http://soundcloud.dev/app/callback.html",
        });

        SC.get('/users/marioochoa/', function(user) {
            $scope.user = user;
            $scope.getTracks();
        });
    };

    $scope.getTracks = function() {
        console.log('getTracks');
    };

    $scope.initialize();
};

A:

Since the SC.get callback is invoked from "outside" Angular, you need to manually trigger a digest cycle so Angular updates the view. In order to do that you should call $scope.$apply():
SC.get('/users/marioochoa/', function(user) {
  $scope.$apply(function() {
    $scope.user = user;
    $scope.getTracks();
  });
});

You can find more information on that matter here.


Q:

How to apply a function to a list only if element is a number

Say I have these lists:
ls1 = {1, 2, 3, 4};
ls3 = {"Chales", 10, 10, 10};

ls5 = ls1 + ls3

ls5 returns {1 + "Chales", 12, 13, 14},
How do I make it return {1, 12, 13, 14} i.e. assume that when there is no valid number (e.g. a negative, no value or a string), apply a zero instead.
I have a huge dataset and sometimes some cells are corrupted so I want to handle automatically.

A:

One can use Replace with the rule Except[_?NumberQ] -> 0 and the explicit level specification {1}.
Replace[ls1, Except[_?NumberQ] -> 0, {1}] + Replace[ls3, Except[_?NumberQ] -> 0, {1}]

{1, 12, 13, 14}

Or slightly shorter:
Plus @@ (Replace[#, Except[_?NumberQ] -> 0, {1}] & /@ {ls1, ls3})


Q:

C++ Compiler Error C2280 "attempting to reference a deleted function" in Visual Studio 2013 and 2015

This snippet is compiled without errors in Visual Studio 2013 (Version 12.0.31101.00 Update 4)
class A
{
public:
   A(){}
   A(A &&){}
};

int main(int, char*)
{
   A a;
   new A(a);
   return 0;
}

while it is compiled with this error in Visual Studio 2015 RC (Version 14.0.22823.1 D14REL):
1>------ Build started: Project: foo, Configuration: Debug Win32 ------
1>  foo.cpp
1>c:\dev\foo\foo.cpp(11): error C2280: 'A::A(const A &)': attempting to reference a deleted function
1>  c:\dev\foo\foo.cpp(6): note: compiler has generated 'A::A' here
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I think that the compiler shipped with Visual Studio 2015 generates the Copy Constructor and marks it as =delete and so I get the error C2280 (which, by the way, I cannot find documented on msdn.microsoft.com).
Now, let's say I have a codebase which is compilable with Visual Studio 2013 (and it works because it relies on the code generated automatically by the compiler) but not compilable with Visual Studio 2015 due to C2280, how can I fix the problem?
I was thinking to declare class A in this way:
class A
{
public:
   A(){}
   A(A &&){}
   A(const A&)=default;
};

am I missing something?

A:

From [class.copy]/7, emphasis mine:

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly.
  If the class definition declares a move constructor or move assignment operator, the implicitly declared copy
  constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if
  the class has a user-declared copy assignment operator or a user-declared destructor.

There is an equivalent section with similar wording for copy assignment in paragraph 18. So your class is really:
class A
{
public:
   // explicit
   A(){}
   A(A &&){}

   // implicit
   A(const A&) = delete;
   A& operator=(const A&) = delete;
};

which is why you can't copy-construct it. If you provide a move constructor/assignment, and you still want the class to be copyable, you will have to explicitly provide those special member functions:
    A(const A&) = default;
    A& operator=(const A&) = default;

You will also need to declare a move assignment operator. If you really have a need for these special functions, you will also probably need the destructor. See Rule of Five.

A:

I had the same problem and it was due to a poorly defined member variable:
double const deltaBase = .001;

Putting this in will cause the copy constructor to be deleted.  Get rid of the "const" and assign in the constructor.

A:

If you write a user-defined move constructor for your class, the copy constructor will be deleted. This is because if a class needs special behaviour for its move constructor, it probably needs some similar behaviour in its copy constructor, so the copy constructor will be deleted to stop you from inadvertently using the default behaviour.
If you want to define your own move constructor and use the default copy constructor, you need to declare it as default, like you suggested in your question:
class A
{
public:
   A(){}
   A(A &&){}
   //I know what I'm doing, compiler, use the default version.
   A(const A&)=default;
};

Note that if you define a custom move constructor, you should think about your assignment operators and destructor as well.


Q:

Constraining UITableViewCell to change when editing

I have a UITableViewCell that has a UIImageView 20 pts in from the left. When I tap "Edit" to edit the contents of my UITableView and the red edit circle comes in from the left, how do I properly set up my constraints so the left of my UIImageView is constrained to the right of that red edit circle view?
Note: I'm doing layout in code, not using Storyboards or xibs

A:

This would be handled automatically if you make sure that your views are subviews of the contentView in the UITableViewCell and your constraints are applied to the contentView.


Q:

Actionscript 3 Injecting string to an existing variable/constant

very simple question that I cannot find an answer to:
private const LEFT_HOUSE_2_X:Number = 445;
private const LEFT_HOUSE_2_Y:Number = 145;
private const LEFT_HOUSE_2_WIDTH:Number = 45;
private const LEFT_HOUSE_2_HEIGHT:Number = 35;

How can I use access the constant above if I am using an iterator:
e.g.
var i:uint = 2;

LEFT_HOUSE_{ i }_X ?

Also to be done with a variable.

A:

using square brackets you can read a const or variable with variable name
this["LEFT_HOUSE_"+i+"_X"]


Q:

Wrapping postback functions to call custom code at execution

Here is my solution for this stackoverflow question.
It is designed to return an onbeforeunload message when the user leaves the page (excluding postbacks). It does this by logging a timestamp each time a .NET control causes a postback (either full or partial using update panels). When this happens, if allowedWaitTime has elapsed, amessage will be returned.
Are there any best or better practices missing from this code and does anyone have an opinion on my style (albeit a small sample)?
(function ($) {

    if (typeof $ !== 'function') {
        throw new Error('jQuery required');
    }

    /* The time in milliseconds to allow between a function call and
       showing the onbeforeunload message. */
    var allowedWaitTime = 100,

        timeStamp = new Date().getTime(),

        // Each function to override
        baseFuncs = {
            __doPostBack: this.__doPostBack,
            WebForm_DoPostBackWithOptions: this.WebForm_DoPostBackWithOptions
        };

    // Set timeStamp when each baseFunc is called
    for (var baseFunc in baseFuncs) {
        (function (func) {
            this[func] = function () {
                var baseFunc = baseFuncs[func];
                timeStamp = new Date().getTime();
                if (typeof baseFunc === 'function') {
                    baseFunc.apply(arguments.callee, arguments);
                }
            }
        })(baseFunc);
    }

    /* Form submit buttons don't call __doPostBack so we'll set timeStamp
       manually on click. */
    $('input[type="submit"]').click(function () {
        timeStamp = new Date().getTime();
    });

    $(this).on('beforeunload', function (e) {

        // Only return string if allowedWaitTime has elapsed
        if (e.timeStamp - timeStamp > allowedWaitTime) {
            return 'message';
        }
    });
}).call(window, jQuery);

A:

Interesting question,
I think the biggest thing is that callee is going the way of the Dodo bird.
JsHint does not like your code because you are using for( .. in .. ) without filtering properties, which is fine since you create the object with Object Notation, and I assume you did not modify the Object prototype. You are also creating functions/closures in a loop. Are you sure you need those closures there?
Other than well commented, and easy to follow, something that I would not mind using in one of my projects.


Q:

htaccess url rewrites and redirects not working

I have a website that was updated. I want to make the old urls work, I want to redirect some of them, so links from google search still work, and rewrite the url for other urls, using .htaccess.
For example:

one rewrite is a.com/services to a.com/consultancy
one redirect is a.com/services/a/b to a.com/consultancy

One extra comlpication: the site sends every request to /index.php because the URLs are not to physical files, but the index.php script does internal routing, using the requested path, to serve the right content.
I'm not sure if I can do a rewrite (services->consultancy) an then another rewrite (consultancy->index.php) in the same htaccess.
Trying this, I'm getting an internal server error 500 for any URL:
RewriteEngine On

#NEW
RewriteCond %{REQUEST_URI} ^services$ [NC]
RewriteRule ^services$ consultancy [L]

#LEGACY
RewriteRule (.*) ./index.php

Also tried the Redirect 301 directive but had no luck, the same error 500.
Any ideas of how to mix rewrites, redirects and the final rewrite to index.php?
Thanks!
Update
For the combination of redirect and rewrite I realized some of the rules are a little different than my original question, and those might be causing problems, here is an example:
# Redirect to show "consultancy" in the URL
RewriteRule ^services/a/b?$ consultancy [QSA,R,L,NC]

# If "consultancy" is in the URL, change it to the real path
# "consultancy" is an alias of the path that should be processed by index.php
RewriteRule ^consultancy/?$ en/consultoria [NC]

# Should get the "en/consultoria" path
RewriteRule ^ ./index.php [L]

The problem with the previous example is that I get the redirect "services/a/b" -> "consultany" OK, but the rewrite "consultancy" -> "en/consultoria" is not done.
Any ideas?

A:

You can use:
RewriteEngine On

#rewrite
RewriteRule ^services/?$ consultancy [L,NC]

#redirect
RewriteRule ^services/a/b/?$ consultancy [L,NC,R=302]

#LEGACY
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


Q:

how to add strings in an array of array in javascript

I have an array of arrays. Say an array of fruits, and each fruit array has an array of properties.
Something like
[["Apple", "seedless", "red"],["Banana", "seedless", "yellow"]]

I now have another array which has an additional property of each of the fruits in the same order as the fruits. say my other array is ["sour","sweet"]. The sour property is to be added to the apple array of properties and sweet is to be added to the banana array of properties so the resultant array looks like
[["Apple", "seedless", "red", "sour"],["Banana", "seedless", "yellow", "sweet"]]

How do I get to the inner array and append it?
I know in the inner array I just have to do
for(var i=0; i<tastePropArray.length; i++){
innerArray.push(tastePropArray(i));
}

but How do I reach/access that inner array?

A:

Try this:
var fruits = [["Apple", "seedless", "red"],["Banana", "seedless", "yellow"]];
for(var i=0; i<fruits.length; i++){
    fruits[i].push(tastePropArray[i]);
}

But I will propose a better datamodel:
Store your fruits like:
var fruits = {
    "Apple": {
         "seeds": "no",
         "colour": "red",
         "taste": "sour"
    },
    "Banana": {
         "seeds": "no",
         "colour": "yellow",
         "taste": "sweet"
    }
};

console.log(fruits.Apple.taste); // sour

Add fruits like:
fruits.StrawBerry = {
    "seeds": "yes",
    "colour": "red",
    "taste": "sweet"
}

Use a for .. in to loop over the fruits.


Q:

Why does nobody attempt to build Charles Babbage's Analytical Engine?

The Difference Engine was built in the 90s.
Why has nobody succeeded in building the Analytical Engine?
Charles Babbage designed the Analytical Engine as a general-purpose computer to succeed  his more limited difference engines. The Analytical Engine would be Turing complete and programmable in an assembler-like language (conditional branches and loops). Unfortunately, like the designs of his Difference Engine(s), it was not build in Charles Babbage's lifetime.
I am interested in reason for this.
Is the design incomplete? If so, what is missing?
The mill (CPU) itself should be impressive enough (as shown in the
Wikipedia article)!

A:

Plan 28 is an ongoing effort to do this.
However, it is hard. Nobody is actually sure how to build it.
Winter 2015:

There has been significant archive activity. The major historical source is the Babbage technical archive held by the Science Museum. The Science Museum digitised the archive in 2012 is now preparing to provide open access to the archive. The Analytical Engine project team has been the main user of the digitised archive under special licence. In the course of the project mismatches have been identified between the digitised material and the existing printed index compiled by the late Allan Bromley and published by the Science Museum in 1991. Referencing anomalies, identification of material omitted from digitisation exercise and other structural issues have become evident. Descriptions of these have been compiled and we are working with Science Museum archivists to resolve and correct these ahead of open access release. The work is detailed and, given the volume of material, substantial. Eye-strain is an ongoing hazard.

Spring 2016:

We have been pecking away at Babbage’s original design drawings for some while now and have found with regret that we are unable to reverse engineer a coherent and consistent understanding of the Analytical Engine from the mechanical drawings alone. There are some 300 drawings and some 2200 Notations – descriptions of the mechanisms using Babbage’s language of signs and symbols. There were three phases of design - early, middle, and late.There is overlap between these, there are ad hoc upgrades, and only fragmentary explanation, where there is explanation at all.

Autumn 2016:

Tim Robinson in the US has been trawling through the entire technical archive and compiling a searchable cross-referenced data base for all surviving technical material. In parallel with this I am conducting a fast-track survey of some twenty manuscript volumes of Babbage’s notebooks focussing on material on his notational language (the Mechanical Notation) that he used to describe his machines – this with a view to reading the notational description of the AE designs using the decoded Notation as an interpretative tool to achieve a deeper understanding of the designs. The data-base and trawling exercise is what has primarily occupied us over the last four months.

March 2018:

The Cambridge manuscript belongs to Babbage’s later period (1850s and early 1860s) when he returned to refine and develop his earlier work. The most substantial single section consists of some 65 manuscript pages the transcription of which is now complete. Tim Robinson has vetted the transcriptions and incorporated them into the database. Preliminary review of this new material suggests that while cryptic in parts it is more coherent than previously thought and contains some potentially dramatic simplifications of implementation. This material will be the focus of close study in due course.

A:

It has been made already (as an emulator)
Thanks to https://www.fourmilab.ch/babbage/
The following is a quote describing their emulator.

Since we're fortunate enough to live in a world where Babbage's dream
has been belatedly realized, albeit in silicon rather than brass, we
can not only read about The Analytical Engine but experience it for
ourselves. These pages include an emulator for The Analytical Engine
and a variety of programs for it. You can run the emulator within a
Web page or as a command-line application on your own computer
(assuming it is equipped with a Java runtime environment). These pages
are a museum, and its lobby is the Table of Contents, to which all
other documents are linked. Rather than forcing you to follow a linear
path through the various resources here, you can explore in any order
you wish, returning to the Table of Contents to select the next
document that strikes you as interesting. Every page has a link to the
Table of Contents at the bottom, so it's easy to get back when you've
finished reading a document or decided to put it aside and explore
elsewhere.

Here you can find the table of contents.
Here you can run the actual emulator.
I'm not knowledgeable enough to say how accurate this emulator is but I'd appreciate if someone from our fine community would comment below and explain how accurate this emulator is and I'll reflect that in my answer.
So go try it out! Enjoy computing in the 1800s! :)

A:

The Difference Engine was built in duplicate; there are good YouTube videos of it. However, the Analytical Engine was a much-more ambitious project, and building any hardware for it must still be in the future.
Its layout reminds one of the Mandelbrot set at 1x scale, so to speak.
See also the mechanical computer made, built by Konrad Zuse, and rebuilt, after World War II.


Q:

What is the correct name for this chord?

C E D B Db F
Here are some attempts at naming this chord from four separate conversion web apps:
Dm9/13/C add(7)
Cmaj9 (11,b9)
Sorry, no matches found
CM11 (b9,add9)
I find it interesting how they each approach it differently, and wanted to see if someone else here has insight into which way is most 'correct' with no context for the chord.
There is one caveat, and that is I'm not interested in finding a better way of naming it by rearranging the note order, that's not the point of this question. The main point is I want to know how to handle adding an extension to a chord structure without removing the adjacent note to the extension. In this example it's the 9 and b9.

A:

Not every simultaneity of notes need be named as a chord. There are 924 possible 6-note selections from 12 notes. For this reason, I prefer to read traditional music notation rather than try to decode chord symbols (or for my own lead sheets, just write the melody, simple chords, major, minor, seventh, nineth, diminished, and the like; if something is more complex, I'd not use a lead sheet even in my shorthand stuff.)
However, this looks a bit like a polychord. There is a B06 (D-F-B) superimposed on a C9 with the fifth and seventh dropped (C-E-Db). However, combining incomplete chords may not describe what's happening harmonically.
Without seeing the context, it's hard to know what's happening musically. Note clusters (in equal temperament) can have more than one name. Take Ab-C-Eb-Gb: this is an Ab7-5, and Ab seventh with a flat fifth. It's rather common in classical music and moves nicely to Db-F-Ab (perhaps inverted), just a variant of a V-I. However if written as Ab-C-Eb-F#, it would normally resolve to G-C-Eb-G (or G-C-E-G) and then to G-B-D-G (or F) as a German Sixth. Sometimes (for various reasons or readability or carelessness) one will be written when the other is meant. It doesn't really matter too much. Chord usage, not chord names are what's important. That's why the key and context are needed to decode the music.
One may also have chords with non-harmonic tones so one could say this is a B diminished with three non-harmonic tone. Or even a  D minor chord with the fifth omitted and a few non-harmonic tones.


Q:

Using Functions complete the function cell so that number are displayed in order

This function sorts 2 numbers and returns them in increasing order. Complete the function call, so that the resulting numbers are displayed in order.

def order_numbers(number1, number2):
 if number2 > number1:
  return number1, number2
 else:
  return number2, number1

___ = order_numbers(100, 99)
print(smaller, bigger)

def order_numbers(number1, number2):
    if number2 > number1:
        return number1, number2
    else:
        return number2, number1
___ = order_numbers(100, 99)
print(smaller, bigger)

A:

def order_numbers(number1, number2):
    if number2 > number1:
        return number1, number2
    else:
        return number2, number1

(smaller, bigger) = order_numbers(100, 99)
print(smaller, bigger)


Q:

Xcode duplicate line

There is a Duplicate command in the Edit Menu (with a default shortcut of ⌘D), but it is (as Halley pointed out) meant for duplication in the Interface Builder part of Xcode.
So, how do you (easily) duplicate a line in Xcode 4?

Related question (with a working answer) for Xcode 3 ... and which does not work for Xcode 4.

Why not just copy & paste?
Because it is tedious and entails too much hand-acrobatics:
either (1): moving to line beginning and then pressing ⇧^E, then copying with ⌘C, moving to new line, alligning cursor, and finally pasting with ⌘V;
or (2): ^A (set cursor to line begining), ^SPACE (set mark), ^E (set cursor to line ending), ⇧^W (Select to Mark; customized), copy, new line, etc.
As Frank Schröder (in the related question) put it:

The whole point is NOT to use the Cmd-C/Cmd-V shortcuts.

A:

Go to this folder which contains dark side of the force:

Xcode 4.2 or prior: /Developer/Library/PrivateFrameworks/IDEKit.framework/Resources
Xcode 4.3 or later: /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources.

Open IDETextKeyBindingSet.plist.
Add a new dictionary and a new command item as the screenshot below (name them what you want):

That's: selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:, deleteBackward:
Restart Xcode and go to Preferences - Key Bindings, search for your command.
Set a key combination for the command:

Finally unleashed the power of key bindings on Xcode... Enjoy it!

A:

Update 2020
Works on Xcode versions: 11.3.1 too
Works in Xcode versions: 7.1, 7.3, 7.3.1, 8.0, 8.1, 8.2, 8.3, 9.0, 9.1, 9.2, 10.0, 10.1, 10.2.1
Instruction

Give permissions to edit the following files. Most of the time OS will not allow you to edit the files.

for 11.3.1 version
sudo chmod 666 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources//IDETextKeyBindingSet.plist

sudo chmod 777 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/

below 11.3 versions

sudo chmod 666 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist

sudo chmod 777 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/

Edit the the file, by writing the following command: (Open it in sublime or text editor if you can)

for 11.3.1
open

/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/

for below versions
open /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/IDETextKeyBindingSet.plist

Append the following xml snippets:

<key>custom</key>
<dict>
    <key>Duplicate Current Line</key>
    <string>moveToBeginningOfLine:, deleteToEndOfLine:, yank:, insertNewline:, moveToBeginningOfLine:, yank:</string>
    <key>Duplicate Lines</key>
    <string>selectLine:, copy:, moveToEndOfLine:, insertNewline:, paste:, deleteBackward:</string>
    <key>Delete Line</key>
    <string>selectLine:, deleteBackward:</string>
</dict>

Screenshots

and Restart Xcode and go to Preferences - Key Bindings, search for the command we typed (Duplicate Lines&Duplicate Current Line).

Thats it.
For unix people to note :-
sudo chmod 755 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/

A:

Ok, I've came up with this:
Version for XCode 11:
selectParagraph:, delete:, undo:, moveRight:, yankAndSelect:

doesn't touch clipboard
works with multiple lines
selects added lines, so can be used multiple times without reselecting
fixed selection in XCode 11
works better with undo

Since I'm applying this change after every XCode update, I've made a script for that. Possibly it can cause some damage, but I've tried to make it relatively safe. It makes a copy of the file, and then replaces line with its copy and additional command using perl. Requires XCode to be installed at /Applications/Xcode.app
cp /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist ~/Desktop/IDETextKeyBindingSet.plist; sudo perl -pi -e 's/\<string\>selectWord:\<\/string>/'$'\<string\>selectWord:\<\/string\>\n\t\t\<key\>Duplicate Selection\<\/key\>\n\t\t\<string\>selectParagraph:, delete:, undo:, moveRight:, yankAndSelect:\<\/string>/g' /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist

Older version
(I'm not sure if the new one is compatible with older versions, so I'll keep it here):
selectParagraph:, delete:, yank:, moveToBeginningOfLine:, setMark:, yank:, moveToBeginningOfLine:, moveLeft:, selectToMark:

and script for older version to avoid manual file editing:
cp /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist ~/Desktop/IDETextKeyBindingSet.plist; sudo perl -pi -e 's/\<string\>selectWord:\<\/string>/'$'\<string\>selectWord:\<\/string\>\n\t\t\<key\>Duplicate Selection\<\/key\>\n\t\t\<string\>selectParagraph:, delete:, yank:, moveToBeginningOfLine:, setMark:, yank:, moveToBeginningOfLine:, moveLeft:, selectToMark:\<\/string>/g' /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist

edit: minor fix
edit2: changed to paragraph selection
edit3: added version for XCode 11


Q:

awk remove mirrored duplicates from 2 columns

Big question:
I want a list of the unique combinations between two fields in a data frame.
Example data:
A   B
C   D
E   F
B   A
C   F
E   F

I would like to be able to get the result of 4 unique combinations: AB, CD, EF, and CF.  Since BA and and BA contain the same components but in a different order, I only want one copy (it is a mutual relationship so BA is the same thing as AB)
Attempt:
So far I have tried sorting and keeping unique lines:
 sort file | uniq

but of course that produces 5 combinations:
A   B
C   D
E   F
B   A
C   F

I do not know how to approach AB/BA being considered the same. Any suggestions on how to do this?

A:

The idiomatic awk approach is to order the index parts:
$ awk '!seen[$1>$2 ? $1 FS $2 : $2 FS $1]++' file
A   B
C   D
E   F
C   F

A:

another awk magic
awk '!a[$1,$2] && !a[$2,$1]++' file


Q:

Can I save frequently used Find & Replace patterns in IntelliJ?

I'd like to be able to build a library or just see a history of regex patterns I've used in Find and Replace.

A:

By default Intellij gives you a list of Recent Searches and Replacements found by clicking on the small search icon on the left of the input bar.


Q:

Boundary of 2D points

Finding the boundary of points can be useful in many fields of computer science. Currently I have visible vertices of a 3D mesh which I projected 2D. The 2D points will be used to obtain the boundary and various types of edges.
An example image obtained from a matlab link on a function obtaining the boundary of points shows boundaries (orange and red) of a set of 2D points. The orange boundary uses a shrink factor and is similar to a boundary created by a convex hull function. In our case we want a more natural boundary of points like the red boundary line (not the one achieved by the convex hull function). The boundary function by matlab is undefined since I am using an older 2014 versions (I assume this is the reason).
Is there another technique/function to achieve the natural boundary line of 2D points? I have tested the convex hull function on the image and it misses a lot of boundary points.
`

A:

It looks like matlabs boundary function is simply returning the boundary of your pointsets alpha shape: https://en.wikipedia.org/wiki/Alpha_shape
There is an implementation for c++ in cgal: http://doc.cgal.org/latest/Alpha_shapes_2/index.html from that documentation we have:

As mentioned in Edelsbrunner's and Mücke's paper [2], one can intuitively think of an α-shape as the following. Imagine a huge mass of ice-cream making up the space ℝ3 and containing the points as "hard" chocolate pieces. Using one of these sphere-formed ice-cream spoons we carve out all parts of the ice-cream block we can reach without bumping into chocolate pieces, thereby even carving out holes in the inside (e.g. parts not reachable by simply moving the spoon from the outside). We will eventually end up with a (not necessarily convex) object bounded by caps, arcs and points. If we now straighten all "round" faces to triangles and line segments, we have an intuitive description of what is called the α-shape of S. Here's an example for this process in 2D (where our ice-cream spoon is simply a circle):


Q:

How to map a continuous variable on a plot as an extra layer?

I'm trying to map a continuous variable on my plot. Perhaps by means of color gradient. But I have not succeeded yet. Any suggestion for adding "gamma" to my plot? I would like also to indicate location of each category (2 levels) on the plot, is that feasible on a single plot?
 plot_2 <- ggplot(data=states_2)+  ggtitle("TBD ")+
 xlab("q")+ylab("r")+ geom_point(aes(x=Q , y= Cor, color=metric))+geom_smooth (aes(x=Q, y=Cor,
color=metric,group=(metric)),
 method="lm", se=FALSE)

   Cor  metric  K     Q  Category     gamma
  0.33  APD    2s   0.4mu   64spp   -0.25282382
  0.23  APD    2s   0.4mu   64spp   -0.653438937
  0.21  APD    2s   0.4mu   64spp   0.799639202
  0.14  APD    2s   0.4mu   64spp   1.039215902
  0.37  APD    2s   0.4mu   64spp   0.207669854

A:

Well, as the comments indicated, you did not give us a lot to go on (you really need to work on your question posing as bdemarest mentioned). So I created some similar fake data (as far as I could figure it out) and did this. The easiest way to bring gamma into this picture is by adjusting the size of the points.
# fake some data into states_2
#
# Cor  metric  K     Q  Category     gamma
# 0.33  APD    2s   0.4mu   64spp   -0.25282382
# 0.23  APD    2s   0.4mu   64spp   -0.653438937
# 0.21  APD    2s   0.4mu   64spp   0.799639202
# 0.14  APD    2s   0.4mu   64spp   1.039215902
# 0.37  APD    2s   0.4mu   64spp   0.207669854
#
n <- 100
cor <- rnorm(n,0.25)
me <- sample(c("APD","APE","APF"),n,replace=T)
kk <- sample(c("2s","3t","4u"),n,replace=T)
qq <- sample(c("0.2mu","0.3mu","0.4mu","0.5mu","0.6mu"),n,replace=T)
ca <- sample(c("64spp","80spp"),n,replace=T)
ga <- rnorm(n,0.5,2)
states_2 <- data.frame(Cor=cor,metric=me,K=kk,Q=qq,Category=ca,gamma=ga)

# plot it
plot_2 <- ggplot(data=states_2)+
  ggtitle("TBD ")+xlab("q")+ylab("cor")+
  geom_point(aes(x=Q , y= Cor, color=metric, size=gamma, alpha=0.5))+
  geom_smooth( aes(x=Q,y=Cor, color=metric,group=(metric)), method="lm",se=FALSE)+
  guides(alpha=F)

print(plot_2)

yields:


Q:

Conditional replacement of objects in a pandas dataframe

I have 2 dataframes df_1 and df_2. Both have an index datetimecodewhich is a pd.datetime64 object, and a temp column. I want to iterate through df_1 and replace all the NaN temperature values with the corresponding temp from 'df_2'.
Something like this:
for index, row in df_1.iterows():
      row['temp'] = df_2[index]['temp'] if row['temp'] ==np.nan

but this is invalid sytax

A:

IIUC
df_1.fillna(df_2, inplace=True)

or
df_1.loc[df_1.temp.isnull(), 'temp'] = df_2.temp

demonstration
tidx = pd.date_range('2016-03-31', periods=5)
df_1 = pd.DataFrame(dict(temp=[1, np.nan, 3, np.nan, 5]), tidx)
df_2 = pd.DataFrame(dict(temp=np.arange(11, 16)), tidx)

df_1.fillna(df_2)

df_1.loc[df_1.temp.isnull(), 'temp'] = df_2.temp

df_1


Q:

Javascript - copying elements to the object's array with callback

let client1 = {
  accounts: Array(),
  accounts_setter: function(obtained_accounts) {
      i = obtained_accounts.length;
      this.accounts = obtained_accounts.slice();
    }
}

function generateAndPushElements(callback) {
 var toPassAccounts =  ['a', 'b', 'c'];
 callback(toPassAccounts);
}

generateAndPushElements(client1.accounts_setter);
console.log(client1.accounts);

<!-- begin snippet: js hide: false console: true babel: false -->

Following code does not fill an object's array, but the process of doing it is in my opinion correct. Do
But the scope is correct.

A:

The problem you have here is that this isn't the right context in your callback. You're not setting the property of client1.
You can fix it with
generateAndPushElements(client1.accounts_setter.bind(client1));

for example.
Be careful if you use this construct in real code with an asynchronous function: your console.log would be misplaced as it logs before any asynchronous task returns.


Q:

AngualrJS ElasticUI dependency injection

I have a question regarding dependency injection in Angular.
I'm using ElasticUI:
https://github.com/YousefED/ElasticUI
The index-name needs to be set inside the  tag.
<body ng-app="tutorial" eui-index="'INDEX_NAME'">

Is it possible to set that INDEX_NAME from "outside" ?
angular.module('tutorial', ['elasticui']). ???

I don't know much about Angular. I'm sorry if this is a stupid question...
Thanks for your help!

A:

It's just like passing a value to a directive. In your controller:
.controller('MyController', function($scope) {
    $scope.indexName = "asdsd";
})

In the HTML:
<body ng-app="tutorial" ng-controller="MyController" eui-index="indexName">


Q:

Why does the Youtube iFrame API not detect state change

I have created a page with the following code to detect state changes to a YT iFrame embed. The player detects the onReady event but not the onStageChange event.
Can anyone explain what I'm missing here?
https://codepen.io/anon/pen/LOZVoX?editors=1001
Code:
<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/CTFtOOh47oo?rel=0&?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>

<script type="text/javascript">

    var tag = document.createElement('script');
    tag.id = 'yt-iframe';
    tag.src = 'https://www.youtube.com/iframe_api';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    console.log('yt scripts loaded');
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('yt-iframe', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }
    function onPlayerReady(event) {
        console.log('video player ready');
    }
    function onPlayerStateChange(event) {
        console.log('state has changed');
        console.log(event.data);
    }
</script>

A:

You have 2 mistakes on your code.
First of all your video url parameters are not correct.
Your url is http://www.youtube.com/embed/CTFtOOh47oo?rel=0&?enablejsapi=1
, thus you pass the parameters rel and amp;?enablejsapi.
Instead your link should be http://www.youtube.com/embed/CTFtOOh47oo?enablejsapi=1, with the parameter enablejsapi.
Your second mistake is that you set your yt script's id to be the same with your iframe's id.
Change the id of the yt script to something else like tag.id = 'yt-script';.
https://codepen.io/anon/pen/yPJJbv?editors=0001


Q:

Html is taking a while to update using jquery

Here is my codepen link: http://codepen.io/johnthorlby/pen/KNQdrJ
This is the code that I have to change my html.
<script>
$(document).ready(function() {
    $("#quote").on("click", function(){
      $("#quote h1").text("\"" + "Here is the quote.");
      $("#quote h4").text("- " + "John Thorlby.")
    });
  });
</script>

When you click the new quote button it is very temperamental and doesn't always work and when it does it takes a while. What am I doing wrong? This is why way I was taught to do it from freecodecamp.com

A:

In your code the button id is quote and so is your div id. So the thing is happening here is you have to click on the div to make the function execute.
Change the button id, then use that id for the click function selector.
Hope this helps..


Q:

The average derivative of an infinite curve in $\mathbb{R}^2$

Is this even a well-formed question, and if so, does it have an approach?
For example, I'd like to say that, by symmetry, a parabola's average derivative would be zero. But that doesn't sit well with me... I mean, how would I even compute such an average??
$$\overline{f'(x)} = \dfrac{\int_{-\infty}^\infty f'(x)\ dx}{\int_{-\infty}^\infty \ dx}$$
That's nonsense, right?

A:

As written the formula is not literally true.  One can write
$$
\lim_{a\to\infty} \frac{ \displaystyle\int_{-a}^a f'(x)\,dx }{\displaystyle\int_{-a}^a 1\,dx}
$$
and that would indeed be equal to $0$, but if you let the upper and lower bounds of integration grow at different rates you'll get something other than $0$.  This is akin to a Cauchy principal value, but with Cauchy principal values you would take limits of each integral separately.


Q:

Output insert and table values when doing insert into

I'm inserting into a table in MS SQL Server 2008 (it's rather a copy of values from the same table) and want to get the output values for the insert. I want to get the id value of the select statement (t.id in the example below), the INSERTED.id works just fine
create table tmp.tbl_inserted (fromId int, toId int)

INSERT INTO mytable (name)
OUTPUT t.id, INSERTED.id INTO tmp.tbl_inserted
SELECT t.name FROM mytable t

Thanks in advance

A:

You can't do it directly from an INSERT:

from_table_name
Is a column prefix that specifies a table included in the FROM clause of a DELETE, UPDATE, or MERGE statement that is used to specify the rows to update or delete.

Note that INSERT isn't mentioned.
What you have to do instead is cheat and use a MERGE:
MERGE INTO mytable m
USING (name,id FROM mytable) t ON 1=0
WHEN NOT MATCHED THEN INSERT (name) VALUES (t.name)
OUTPUT t.id, INSERTED.id INTO tmp.SizeCurveGroup_inserted
;


Q:

Removing brackets and inverted quotations when writing a list to a csv file PYTHON

I'm currently writing a list to a csv file. I have done that correctly.
(Hypothetically) my work looks something like this:
stuff = [34,87,34,43,23,32]
with open("typer.txt", "w") as myTyper:
    myTyperSpells = csv.writer(myTyper)
    myTyperSpells.writerow([stuff])

This list is successfully written to the text file "typer". However, it  appears like this:
"[34, 87, 34, 42, 23, 32]"

Is it possible to remove the inverted commas, square brackets and spaces so that it appears like this in the text file instead?:
34,87,34,42,23,32

Any help will be useful...thanks!

A:

Remove the square brackets around stuff when you write the row.
E.g.
myTyperSpells.writerow(stuff)

As it is you're putting your list inside another list


Q:

Understanding the notation involved with differential of quaternion Exponential map

I am reading a paper that describes the differential of a unit quaternion curve.
$dF_p$ denotes the differential of the following map at $p$
$$F:\mathbb{R}^n \to \mathbb{R}^m$$
Page 4 of the paper describes the Exponential map $exp : \mathbb{R}^3 \to S^3$ as follows
$$ exp(x,y,z)  =
    \begin{cases}
      (cos||v||, \frac{sin||v||}{||v||}.(x,y,z)) & if ~~v=(x,y,z)\ne (0,0,0) \\
      (1,0,0,0)        &  if ~~v=(x,y,z) = (0,0,0)
    \end{cases}
$$
Page 6 presents the following figure and an accompanying text explanation to help interpretation of $dF_p$

Explanation:

In the above explanation what is $T_{log~q}\mathbb{R}^3$ ?
In the diagram, I can see $T_{1}S^3$ (tangent space to the standard quaternion (1,0,0,0)) and $T_{q}S^3$ (tangent space to a general quaternion $q$). But I do not know what is $T_{log~q}\mathbb{R}^3$.

A:

$T_{\log q} \mathbb R^3$ is the local tangent space defined at $\log q$, which is isomorphic to $\mathbb R^3$ defined by its tangent vectors $e_1$, $e_2$ and $e_3$.
In the picture you see that $d \exp_{\log q}$ is sending the tangent vectors $e_1$, $e_2$ and $e_3$ attached at $\log q$ to a tangent space at $q \in S^3$ (depicted as a plane) defined by tangent vectors $a_1$, $a_2$ and $a_3$ passing through $q$ where $a_i = d \exp_{\log q}( e_i) \in T_q S^3$.


Q:

Python global variable

def say_boo_twice():
  global boo
  boo = 'Boo!'
  print boo, boo

boo = 'boo boo'
say_boo_twice()

The output is

Boo! Boo!

Not as I expected. Since I declared boo as global, why is the output not:

boo boo boo boo

A:

You've changed boo inside your function, why wouldn't it change? Also, global variables are bad.

A:

Because you reassign right before hand.  Comment out boo = 'Boo!' and you will get what you describe.
def say_boo_twice():
   global boo
   #boo = 'Boo!'
   print boo, boo

boo = 'boo boo'
say_boo_twice()

Also that global boo is unnecessary, boo is already in global scope.
This is where the global makes a difference
def say_boo_twice():
   global boo
   boo = 'Boo!'
   print boo, boo

say_boo_twice()
print "outside the function: " + boo #works

Whereas:
def say_boo_twice():
   #global boo
   boo = 'Boo!'
   print boo, boo

say_boo_twice()
print "outside the function: " + boo # ERROR.  boo is only known inside function, not to this scope

A:

You are re-assigning boo after you declare it as global, so the value is the last one you assigned to it. If you removed line three, you would get the output you expect.


Q:

Weapon class firing logic in JavaScript

I'm making a program to compare Borderlands 3 weapon damage over time in a graphic. There's still some work to be done, like implementing elemental damage, but I'd like to know if I'm doing a good job for now regarding the main firing logic.
My biggest concerns are:

General readability.
WeaponReload and WeaponFire extend WeaponAction, a class containing the properties .startTime, .endTime and .duration (included after the Weapon class code) and both are being treated as if they're the same. I think some other languages can do something similar using structs and protocols to check conformity and I'm not sure if this is the right way to do it in JavaScript.
I don't know whether I'm doing a good use of the try {...} catch {...} statement in Weapon.fullAuto or if this logic could be improved upon using other methods.

class Weapon {
    constructor (damage, fireRate, reloadSpeed, magazineSize, elementalDamage, elementalChance) {
        this.damage = damage
        this.fireRate = fireRate
        this.reloadSpeed = reloadSpeed
        this.magazineSize = magazineSize
        this.elementalDamage = elementalDamage
        this.elementalChance = elementalChance

        this.bulletsLeftInMagazine = magazineSize
    }
    get timePerShot () {
        return 1 / this.fireRate
    }
    fire (startTime = 0) {
        if (this.bulletsLeftInMagazine < 1)
            throw new Error("Not enough bullets in the magazine")

        let whenCanFireAgain = startTime + this.timePerShot

        --this.bulletsLeftInMagazine

        return new WeaponShot(startTime, whenCanFireAgain, this.damage)
    }
    reload (startTime = 0) {
        let whenCanFireAgain = startTime + this.reloadSpeed

        this.bulletsLeftInMagazine = this.magazineSize

        return new WeaponReload(startTime, whenCanFireAgain)
    }
    fullAuto (duration, startTime = 0) {
        let localActionStartTime = 0,
            globalActionStartTime = startTime,
            actions = []

        while (duration > localActionStartTime) {

            let localActionEndTime,
                globalActionEndTime,
                action

            try {
                action = this.fire(globalActionStartTime)
            } catch {
                action = this.reload(globalActionStartTime)
            }

            actions.push(action)

            localActionStartTime += action.duration
            globalActionStartTime += action.duration

        }

        return actions
    }
}

class WeaponAction {
    constructor (startTime, endTime, damageDealt) {
        this.startTime = startTime
        this.endTime = endTime
        this.damageDealt = damageDealt
    }
    get duration () {
        return this.endTime - this.startTime
    }
}

A:

I understand semicolons in JavaScript are optional, however I believe you should always use them. It's easy to have something break later on because you neglected a semi-colon and it lost the whitespace which saved it before in a compression/generation/eval parse.
You could declare the timePerShot as a variable, to ensure the amount is not being calculated on every call (Although I'm pretty sure the parser or cache already solves this).
Use exceptions / errors in exceptional cases only. An example being making an HTTP call; The target could not exist, the internet could be down, or other cases that are out of your control.
Catching exceptions is also going to be very slow. You can return a value such as false instead. And/or you could do the check outside of the function.

A:

There is not much I would add to dustytrash's answer:

prefer const over let when a variable does not change
use blank lines only for creating logical regions; to me, an assignment to an instance variable is not a logical region

reload (startTime = 0) {
    const whenCanFireAgain = startTime + this.reloadSpeed;
    this.bulletsLeftInMagazine = this.magazineSize;
    return new WeaponReload(startTime, whenCanFireAgain);
}

instead of..

reload (startTime = 0) {
    let whenCanFireAgain = startTime + this.reloadSpeed

    this.bulletsLeftInMagazine = this.magazineSize

    return new WeaponReload(startTime, whenCanFireAgain)
}


Q:

how do i add the latest folder made in a pen drive to my batch file command

eg my latest folder made is 20150106 so i want to use it as an existing file's name as cd c:/20150106
i want cd c:/%latest_folder_name%
i have many folders made ALMOST daily as 20150103 , 20150104 as a backup so now the task is to copy the latest folder to d drive from the inserted pen drive. please don't talk any thing of date command bcoz its not the date command that matters i just want the latest folder's name.
please help
my job is of great importance i tell u
i have already tried posting on yahoo answers
plzzz help me
i just want the latest folder's name extracted automatically

A:

get all folders starting with "20" (/ad= Attribute Directory) (/b print name only)
dir /ad /b 20*

get them sorted by name:
dir /ad /b 20* |sort

or
    dir /ad /b /on 20*
get the latest of it (by name, not by "modified date")
for /f "tokens=*" %%i in ('dir /ad /b /on 20*') do set latest=%%i

If you want the last modified folder, use (
dir /ad /b /o-d /tw

(for explanation of the parameters see dir /?)


Q:

php select multiple checkboxes

i have this code, which helps me to retrieve all table fields and associate a check button to them, but this code is generating the same name, i mean it shows me all the fields, but named the same... id
I need their particulatr name..
can you please see what's wrong?
Thanks..
        <form action='report.php' method='post'>

<?php // Script 12.7 - sopping.php

$db = mysql_connect('localhost', 'root', '');
mysql_select_db('db_up', $db);

echo "
";

$result = mysql_query("SELECT * FROM hostess");
$numrows = mysql_num_rows($result);
$numfields = mysql_num_fields($result);

// show headers
echo '

';
for ($field = 0; $field < $numfields; $field++) {
    $field_name = mysql_field_name($result, $field); // instead of $i
    echo '<input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '	';
}

echo '

';

echo '
';
for ($row = 0; $row < $numrows; $row++) {
    $data = mysql_fetch_assoc($result);
    echo '
';
    for ($field = 0; $field < $numfields; $field++) {
        $field_name = mysql_field_name($result, $field);
        if (isset($_POST['checkbox'][$field_name])) {
            echo '' . $data[$field_name] . '	';
        }
    }
    echo '
';
}
echo '
';
echo '
';

?>
<input type='submit' value='Submit' />
</form>

A:

The second argument of the mysql_field_name function isn't defined so I am pretty sure PHP is assuming you mean 0 and is returning the first fieldname only. Use the variable you defined ($field) as the index.
Should be:
for ($field = 0; $field < $numfields; $field++) {
    $field_name = mysql_field_name($result, $field); // instead of $i
    echo '<input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '	';
}


Q:

How to enable "show method chain hint" in IntelliJ?

I am using JDK 8 and using reactive programming(spring webflux). I want to know how to enable "show method chain hint" in IntelliJ ?

A:

With IntelliJ 2019.3, one should set for inlay hints (in Settings | Editor | Inlay hints | Java):


Q:

Issues with requestAnimationFrame

I have an issue:

document.querySelector('div').addEventListener('mousedown', function(){
        hello = true
        document.body.addEventListener('mousemove', function(e){
            if (hello) {
                document.querySelector('div').style.left = (e.clientX - 12.5) + 'px'
                document.querySelector('div').style.top = (e.clientY - 12.5) + 'px'
            }
        })
        this.addEventListener('mouseup', function(e){
            hello = false
            posY = Math.floor(parseInt(this.style.top))
            function Fall() {
                posY++
                document.querySelector('div').style.top = posY + 'px'
                if (posY != parseInt(window.innerHeight) - 25) requestAnimationFrame(Fall)
            }
            Fall()
        })
    })
body {
  margin:0;
  position:absolute;
  height:100vh;
  width:100vw;
  overflow:hidden
}

div {
  position:absolute;
  height:25px;
  width:25px;
  border:1px #000 solid;
  bottom:0
}
div:hover {
  cursor:pointer;
}

In this code (also on jsFiddle, when I drop the div, I want the div to fall, and stop at the ground.
The first time, it works. But then, requestAnimationFrame is faster, it's like the first one isn't done...? And after that, the div didn't stop at the ground :(
Do I have to use setInterval instead of requestAnimationFrame?

A:

Whenever the div is clicked (mousedown) theres another listener assigned. When you stop clicking, these listeners are all executed in order, so at the second click, there will be two loops running, after the third there will be three loops running and so on. You may just assign the listener once:
var hello,posY;

document.querySelector('div').addEventListener('mousedown', function(){
  hello = true;
});

document.body.addEventListener('mousemove', function(e){
    if (hello) {
        document.querySelector('div').style.left = (e.clientX - 12.5) + 'px';
        document.querySelector('div').style.top = (e.clientY - 12.5) + 'px';
    }
});

document.querySelector('div').addEventListener('mouseup', function(e){
    hello = false;
    posY = Math.floor(parseInt(this.style.top));
    function Fall() {
        posY++;
        document.querySelector('div').style.top = posY + 'px';
        if (posY < parseInt(window.innerHeight) - 25) requestAnimationFrame(Fall);
    }
    Fall();
});

And please always end a statement with a semicolon...


Q:

GAE Blobstore Error: NOT_FOUND servlet

I'm trying to user the BlobstoreService in order to upload images to my application.
According to the GAE API this is how you should do it:
<form action="<%= blobstoreService.createUploadUrl("/upload") %>" method="post" enctype="multipart/form-data">
    <input type="file" name="myFile">
    <input type="submit" value="Submit">
</form>

My problem is that I cannot use JSP because I'm using phonegap to create an android app and JSPs are not supported so I do this in another way, I have one servlet that receive the request, genarated the URL and forward the request to the generated URL like this:
GetBlobstoreServiceUrlServlet:
String url = blobstoreService.createUploadUrl("/AddDogPictureServlet");
int ahUploadIndex = url.indexOf("/_ah/upload");
url = url.substring(ahUploadIndex);
ServletContext context = getServletContext();
RequestDispatcher rd = context.getRequestDispatcher(url);
rd.forward(request, response);

This is working perfectly when I run it on my local computer but when I upload it to the GAE I'm getting "Error: NOT_FOUND" on this servlet only.
I have other serlets and all of them are working fine.
I checked the web.xml file and the servlet mapped correctly (otherwise it would not worked locally):
<servlet>
    <servlet-name>GetBlobstoreServiceUrlServlet</servlet-name>
    <servlet-class>Servlets.BlobstoreServlets.GetBlobstoreServiceUrlServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>GetBlobstoreServiceUrlServlet</servlet-name>
    <url-pattern>/GetBlobstoreServiceUrlServlet</url-pattern>
</servlet-mapping>

Is there another way to achieve this goal?

A:

The problem is that, in production, the generated blob upload Urls (createUploadUrl(..)) are on servers separate from your app servers. OTOH requestDispatcher.forward(..) only works within the same servlet container. This works on development server because blob upload urls are simulated and run in the same servlet container.
The solution is either to:

forward the whole request via Url Fetch (which makes a full new outgoing Http request), or
preferably make upload in two steps: first get Upload url from server, then upload blob to that url.


Q:

How to use SUPPLICANT_STATE_CHANGED_ACTION WiFi BroadcastReceiver - android

I want to show the connection process on the screen when my device is connecting to the wifi network. SUPPLICANT_STATE_CHANGED_ACTION is provided by WifiManager but i don't know how to use it. Can anyone help me please?

A:

You can indeed use the broadcasted intents for SUPPLICANT_STATE_CHANGED_ACTION:
The app needs the permission in its Manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Then register for the system broadcast:
    MyWifiStateReceiver handler = new MyWifiStateReceiver();
    context.registerReceiver(handler, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));

the registerReceiver() needs an instance of a class implementing BroadcastReceiver as its first argument. In that code you can act on the Wifi state changes by overriding the onReceive method. For example
public class MyWifiStateReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
        {
            SupplicantState state = (SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch(state)
            {
                case COMPLETED:
                case DISCONNECTED:
                    ...
            }
        }
    }
}

For the possible Wifi state values, see http://developer.android.com/reference/android/net/wifi/SupplicantState.html

A:

I don't know of a callback method that lets you know when the wifi status has changed.  I polled the information using a Handler running in the background.
Add the handler to your class.
private WifiStatusHandler wifiStatusHandler = new WifiStatusHandler();

Start it by calling
wifiStatusHandler.start();

The code I used is below.
/**
 * Checks for wifi status updates.
 */
private class WifiStatusHandler extends Handler {
    private boolean running = false;

    public void handleMessage(Message message) {
        if (running) {
            //check wifi status here
            WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            int curWifiState = wifiMgr.getWifiState();
            SupplicantState info = wifiMgr.getConnectionInfo().getSupplicantState();
            WifiInfo curWifi = wifiMgr.getConnectionInfo();
            Log.i(TAG,"WIFI STATE = " + info.toString());
            //update the TextView etc.
            sleep();
        }
    }

    private void sleep() {
        removeMessages(0);
        sendMessageDelayed(obtainMessage(0), REFRESH_DELAY);
    }

    public synchronized void start() {
        running = true;
        removeMessages(0);
        sendMessageDelayed(obtainMessage(0), 0);
    }

    public synchronized void stop() {
        running = false;
    }
}


Q:

Drunken sailor's Random Walking

A drunken walker is on $x=0$, and if $x<0$, he falls and he dies.(Once he gets position $x<0$, he dies permanently.)
There is $0<p<1$ chance to move right ($x \rightarrow x+1$), and $1-p$ chance to move left
($x \rightarrow x-1$).
(1) After $n$th step, what is the probability he is still alive?
(2) I have no idea to how to define probability he is still alive after infinite iteration, since there are infinite state and I can't convince this probability will be limit of (1) when $n$ goes $\infty$. So how to define that probability precisely and why it will be limit of (1)?

A:

The generating function of the first hitting time $T$ of $-1$ starting from $0$ is $$E(s^T)=\frac{1-\sqrt{1-4pqs^2}}{2ps}=\sum_{n\geqslant0}\frac1{n+1}p^nq^{n+1}{2n\choose n}s^{2n+1},$$ where $q=1-p$. Thus, the probability to be still alive at time $2n+1$ is $$P(T\geqslant2n+3)=1-P(T\leqslant2n+1)=1-\sum_{k=0}^{n}\frac1{k+1}p^kq^{k+1}{2k\choose k}.$$ The probability to stay alive forever is $0$ if $p\leqslant\frac12$ and $1-(q/p)=(2p-1)/p$ if $p\gt\frac12$.


Q:

C warning: incompatible pointer types passing

I keep getting an error when trying to compile my code.  The error is as follows :
warning: incompatible pointer types passing
  'void *(threadData *)' to parameter of type 'void * (*)(void *)'
  [-Wincompatible-pointer-types]
        pthread_create(&threads[id], NULL, start,&data[id]);

I'm trying to pass a struct to the function, void * start(threadData* data), and this keeps throwing me off.  Any ideas?

A:

It's complaining about the thread function (bound to the third parameter of pthread_create), you can modify that to take a void * argument and then cast it back before doing anything with it:
void *start (void *voidData) {
    threadData *data = voidData;
    // rest of code here, using correctly typed data.

You may also opt to coerce the data pointer (fourth parameter) to the expected type:
(void*)(&(data[id]))

but I don't think that's necessary since a void * is supposed to be freely convertible to and from most other pointers.

You can see the problem in this small yet complete program:
#include <stdio.h>
#include <string.h>
#include <pthread.h>

struct sData { char text[100]; };

void *start (struct sData *data) {
        printf ("[%s]\n", data->text);
}

int main (void) {
        struct sData sd;
        pthread_t tid;
        int rc;

        strcpy (sd.text, "paxdiablo");
        rc = pthread_create (&tid, NULL, start, &sd);
        pthread_join (tid, NULL);

        return 0;
}

When compiling that, you see:
prog.c: In function 'main':
prog.c:20:2: warning: passing argument 3 of 'pthread_create' from
             incompatible pointer type [enabled by default]
             In file included from prog.c:3:0:
                 /usr/include/pthread.h:225:12: note: expected
                     'void * (*)(void *)' but argument is of type
                     'void * (*)(struct sData *)'

Keep in mind that it's just a warning, not an error but, if you want your code to compile cleanly, it's worth getting rid of. Making the changes mentioned at the top of this answer (bar the data parameter casting) gives you the following thread function:
void *start (void *voidData) {
        struct sData *data = voidData;
        printf ("[%s]\n", data->text);
}

This compiles without warnings, and runs just fine.


Q:

Error when add node programmatically

I'm new in Drupal, and I want to create a website which get all news data from my old site.
I tried to use node API to create node base on my old data. It worked but when I edit my new node, I get an error : "Alias already in use".
I tried adding simple node with title and body and get the same issue.
Please help me!!
Many thanks!

A:

you probably have duplicates nodes. Check "Generate automatic URL alias" box in your node path settings to generate an "mynode-1" for debuging


Q:

Finding the total number of roots of a graph

So I was given this graph:

and I was told the function was defined as:
$$f(x) = (x-c_1)(x-c_2)...(x-c_n)$$
Then I was told to find n. So I assumed they meant the total number of real roots. So since from the graph I could tell there were 2 real roots, then it was impossible for it to be 2 reals roots and 1 non-real root. So the answer must be 3 real roots. It was correct, but their explanation was:

The graph crosses the x‑axis at −10, so f must have a positive odd number of factors corresponding to that x‑intercept
The graph crosses the x‑axis at 15, so f must have a positive even number of factors corresponding to that x‑intercept
There are no other x‑intercepts, so this accounts for all the factors. The total number of factors of f is, therefore, an odd number plus an even number, and must be at least 3.

I don't understand their explanation, because they first say f must have a positive odd number of factors, then they say it has positive even number of factors, and then they say there are no other x-intercepts? when there is another third factor? Does anyone know what is meant by that explanation?

A:

The third root comes from the fact that one of the zeros is tangent to the x-axis, i.e. it is touching the x axis but not crossing through. Kind of odd, but let me try to explain why.
Imagine the function was shifted down a small amount, then there would clearly be three zeros. Now let's slowly shift the function back to its original position. As you do, the two zeros on the right would get closer and closer to each other until finally when the function finally reaches its original position, both zeros have merged into one single position. That's why it seems like the third zero is kind of "hidden".


Q:

How to create a folded surface from a contour

I am computing the coordinates of a circuit on the sphere using several (heavy) pgfmath macros. This results in a costly production of what is basically a table of two dimensional coordinates.
Using commands like
\draw[green] plot file {foo.table};

I can produce the contour of this picture (the solide line).
But to produce the folded area attached to the center of the sphere, I need to use the data computed by pgfmath directly in a loop and store the position of the point number n to plot the point number n+1 (the area is made of triangles drawn with the options opacity=0.5 to give the expected volume effect).
How could I use the file foo.table to draw the triangles ?
Here is the code of a MWE containing the coordinates of the contour.
\documentclass{article}
\usepackage{filecontents}
\usepackage{tikz}
\begin{filecontents}{foo.table}
-2.29732 0.562597
-2.46077 0.625805
-2.57584 0.71416
-2.63998 0.816141
-2.66182 0.920619
-2.65234 1.02147
-2.62076 1.11484
-2.57249 1.19958
-2.51155 1.27533
-2.43976 1.34266
-2.3593 1.40214
-2.27191 1.45466
-2.18021 1.50059
-2.08669 1.54079
-1.99478 1.57552
-1.90685 1.60501
-1.82599 1.63018
-1.75452 1.65186
-1.69393 1.67119
-1.64512 1.68957
-1.60823 1.709
-1.58249 1.73134
-1.56535 1.75887
-1.55367 1.79362
-1.54343 1.83718
-1.53004 1.89022
-1.50929 1.95238
-1.47762 2.02234
-1.43256 2.09793
-1.37379 2.17617
-1.3026 2.25408
-1.22121 2.32878
-1.13342 2.39764
-1.04333 2.45867
-0.955271 2.51064
-0.873334 2.55296
-0.800973 2.58505
-0.740967 2.60705
-0.694815 2.61903
-0.663029 2.621
-0.645284 2.61303
-0.640066 2.59519
-0.645636 2.56722
-0.659579 2.52956
-0.679626 2.48256
-0.703663 2.42761
-0.729928 2.36629
-0.756862 2.3006
-0.783243 2.23337
-0.808042 2.16758
-0.830145 2.10622
-0.848038 2.0521
-0.860296 2.00728
-0.865032 1.97321
-0.86053 1.95058
-0.845243 1.93878
-0.818525 1.93681
-0.780152 1.94306
-0.730695 1.95537
-0.671749 1.97182
-0.604967 1.98989
-0.53254 2.00757
-0.456746 2.02293
-0.379503 2.03405
-0.302492 2.03917
-0.227065 2.03719
-0.154141 2.02689
-0.0846459 2.00691
-0.0194568 1.97702
0.0402252 1.9364
0.0927954 1.88509
0.136014 1.82341
0.166822 1.75208
0.182072 1.67283
0.177692 1.58763
0.150057 1.49981
0.0962308 1.41353
0.0152284 1.33285
-0.0912037 1.26258
-0.218461 1.20699
-0.358397 1.16837
-0.50119 1.14729
-0.637133 1.14165
-0.758478 1.14754
-0.860913 1.15971
-0.943287 1.17277
-1.0075 1.18142
-1.05683 1.18161
-1.0954 1.17012
-1.1276 1.14484
-1.15794 1.10468
-1.19054 1.05006
-1.23024 0.982231
-1.28177 0.903583
-1.35095 0.818083
-1.44357 0.731335
-1.5653 0.650635
-1.71889 0.5845
-1.90224 0.542744
-2.10245 0.534021
-2.29732 0.562597
\end{filecontents}
\begin{document}
\tikz{
\draw circle(3);
\node {$\bullet$};
\draw[green] plot file {foo.table};
}
\end{document}

A:

That's actually a duplicate of Drawing a 3D cone.  But it's a fun duplicate, and some changes are required to have the result look similar to what you want.  For example:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing}

\tikzset{
  to center/.style={
    decorate,
    decoration={show path construction,
      lineto code={
        \path [fill=green!20,opacity=0.5,line join=round]
        (\tikzinputsegmentlast) -- (\tikzinputsegmentfirst)
        -- (center) -- cycle;
      }}}}

\begin{document}
\begin{tikzpicture}
  \draw circle(3);
  \coordinate (center) at (0,0);
  \node at (center) {$\bullet$};

  \fill [green!30, to center]
  plot  file {foo.table}  -- cycle;

  \draw[green] plot file {foo.table};
\end{tikzpicture}
\end{document}

Output:


Q:

Create "refresh token" action filter

I am using idenity server 3 authentication.
I have to implement refresh token logic.
AccessTokenLifetime is 1 hour, and after that time I want to update access token with refresh token.
I want do this only once, by using filter in mvc. My idea is to check if token has expired, and if yes that get new token.
This is my code, I want to know if this is best practice or you maybe have better idea?
  public class RefreshTokenActionFilter : FilterAttribute, IActionFilter
        {
            void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
            {
                var user = filterContext.HttpContext.User as ClaimsPrincipal;
                var request = filterContext.HttpContext.Request;
                RefreshToken(user, request);
            }

            void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
            {
            }

            private  void RefreshToken(ClaimsPrincipal User, HttpRequestBase Request)
            {
                var claims = ClaimsPrincipal.Current.Claims;
                var refreshToken = claims.Where(c => c.Type == AuthenticationValues.RefreshTokenKey).Select(c => c.Value).SingleOrDefault();
                long epoch = Convert.ToInt64((claims.Where(c => c.Type == AuthenticationValues.ExpiresAtEpochKey).Select(c => c.Value).SingleOrDefault()));

                // 60 seconds is tolerance
                if (refreshToken != null && epoch - 60 < DateTime.UtcNow.ToEpochTime())
                {
                    var tokenClient = new TokenClient(ApplicationConfiguration.IdentityServerToken,
                                      AuthenticationController.ClientApplicationId,
                                      AuthenticationController.ClientApplicationSecret);

                    var response = (tokenClient.RequestRefreshTokenAsync(refreshToken)).Result;
                    var user = User as ClaimsPrincipal;
                    var identity = user.Identity as ClaimsIdentity;

                    //Remove old tokens:
                    var oldRefreshToken = user.Claims.Single(c => c.Type == AuthenticationValues.RefreshTokenKey);
                    var oldAccessToken = user.Claims.Single(c => c.Type == AuthenticationValues.AccessTokenKey);
                    var oldExpiresAt = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtKey);
                    var oldEpoch = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtEpochKey);
                    identity.RemoveClaim(oldRefreshToken);
                    identity.RemoveClaim(oldAccessToken);
                    identity.RemoveClaim(oldExpiresAt);
                    identity.RemoveClaim(oldEpoch);

                    //Add new tokens:
                    identity.AddClaim(new Claim(AuthenticationValues.AccessTokenKey, response.AccessToken));
                    identity.AddClaim(new Claim(AuthenticationValues.RefreshTokenKey, response.RefreshToken));
                    identity.AddClaim(new Claim(AuthenticationValues.ExpiresAtKey, (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
                    identity.AddClaim(new Claim(AuthenticationValues.ExpiresAtEpochKey, (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToString()));

                    var authenticationManager = Request.GetOwinContext().Authentication;

                    authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
                                                                                new ClaimsPrincipal(identity),
                                                                                new AuthenticationProperties { IsPersistent = true });
                }
            }
        }

A:

I can see repetitive code which you can fix easily..
Before
//Remove old tokens:
var oldRefreshToken = user.Claims.Single(c => c.Type == AuthenticationValues.RefreshTokenKey);
var oldAccessToken = user.Claims.Single(c => c.Type == AuthenticationValues.AccessTokenKey);
var oldExpiresAt = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtKey);
var oldEpoch = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtEpochKey);
identity.RemoveClaim(oldRefreshToken);
identity.RemoveClaim(oldAccessToken);
identity.RemoveClaim(oldExpiresAt);
identity.RemoveClaim(oldEpoch);

After
var tokens = user.Claims
    .Where(c =>
        c.Type == AuthenticationValues.RefreshTokenKey ||
        c.Type == AuthenticationValues.AccessTokenKey ||
        c.Type == AuthenticationValues.ExpiresAtKey ||
        c.Type == AuthenticationValues.ExpiresAtEpochKey);

foreach (var token in tokens)
{
    identity.RemoveClaim(token);
}

You have filter claims by its type many times, which is similar code. You can get rid of duplicate code by introducing a method. I am not sure about the return or parameter type but it look somehow like below.
public static string GetClaimsType(string type)
{
    return ClaimsPrincipal.Current.Claims.Where(c => c.Type == type).Select(c => c.Value).SingleOrDefault();
}

Now your code will be much cleaner and shorter..
Before
var claims = ClaimsPrincipal.Current.Claims;
var refreshToken = claims.Where(c => c.Type == AuthenticationValues.RefreshTokenKey).Select(c => c.Value).SingleOrDefault();
long epoch = Convert.ToInt64((claims.Where(c => c.Type == AuthenticationValues.ExpiresAtEpochKey).Select(c => c.Value).SingleOrDefault()));

After
var refreshToken = GetClaimsType(AuthenticationValues.RefreshTokenKey);
long epoch = Convert.ToInt64(GetClaimsType(AuthenticationValues.ExpiresAtEpochKey));


Q:

Do I need to destroy objects in PHP after using them?

How crucial is object destruction in PHP? is it important to destroy objects in PHP after using them? because unlike java, PHP doesn't have a garbage collector (nothing that I know of)

A:

You don't need to destroy objects in the general case, and PHP certainly does have a garbage collector. Moreover, most simple scripts would not even really need one because the whole environment is torn down and rebuilt for every HTTP request; the garbage collector helps those scripts that would run out of memory while serving a single request.
Exceptions to the general case:
You might want to "lose" all references to objects that consume a large amount of memory and/or wrap unmanaged resources; this is usually as easy as
$largeObject = null; // reference to previous value lost

If that was the last reference to $largeObject, then:

PHP will immediately call the destructor (if one exists); you might want to do for objects which are wrapping unmanaged resources (e.g. database connections, sockets, etc) if your script is long-lived.
The memory that the object takes up will now be eligible for garbage collection. However, collection will not occur on the spot but at some later point where more memory is required (although you can call gc_collect_cycles to force garbage collection at any time).

Of course all of this does not come into consideration in the typical case of "service a request and then exit".


Q:

Servlet unavailable in AppEngine with Android Client

I am getting the following info log in GAE's console:
"POST /xxx HTTP/1.1" 200 133 - "Apache-HttpClient/UNAVAILABLE (java 1.4),gzip(gfe)"
I can not understand if the servlet is not available, why is "200" being returned. I checked web.xml file for servlet mapping and they seem fine. What else could be causing it. Is it even an error on GAE or is it due to client error.

A:

The string "Apache-HttpClient/UNAVAILABLE (java 1.4)" is the client's user agent string. It's not an error - it's the identification the client sent to the server. In this case, 'UNAVAILABLE' is probably in place of the version number of the library.


Q:

Python returns 5 digit timestamp, what is this?

I'm a PHP programmer doing a bit of Python (3.4) just because it's way easier to do it in Python.
My script converts a .xlsx file, into many .csv files (one .csv per sheet).
Here is the code:
wb = xlrd.open_workbook(filepath)

for i in range(0, wb.nsheets):

    sh = wb.sheet_by_index(i)
    sheet_name = sh.name
    sheet_name = sheet_name.replace(" ", "_");
    fp = open(sheet_name+'.csv', 'at', encoding='utf8')
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL)

    for row_num in range(sh.nrows):
        wr.writerow(sh.row_values(row_num))

    fp.close()

Full code here: https://github.com/xtrimsky/xlsx_to_csv
This works well, except that I have a field that is a date, in excel it shows for example: 01/01/2009
But the final csv, contains a number that is 39814. What is this please, what can I do with it ? 01/02/2009 is 39815.
Is it a number I can use to find the unix timestamp ? Or is it an issue and I should change my script ? I would feel safer if it would just return the string "01/01/2009".
Can someone please help me understand what I am dealing with ?

A:

If 39814 maps to 2009-1-1 and 39815 maps to 2009-1-2, then it looks like the ordinal is counting the number of days since 1899-12-30:
In [57]: DT.date(1899,12,30) + DT.timedelta(days=39814)
Out[57]: datetime.date(2009, 1, 1)

See Why 1899-12-30!?
To convert the Excel number to a Unix timestamp, you could use the timetuple method to convert the datetime.date object to a timetuple, and then time.mktime to convert it to a timestamp (seconds since the Epoch):
In [80]: import time

In [81]: time.mktime((DT.datetime(1899,12,30) + DT.timedelta(days=39814)).timetuple())
Out[81]: 1230786000.0


Q:

Get a dictionary's key by value

Possible Duplicate:
Efficient bidirectional hash table in Python?

I'm working on an AST parser, that parses python code. First, I turn the python code into an AST with a call to compile.
In doing this, I need to ensure that I don't compile the same imported module twice, even if there are two calls to import it.
Currently, I can detect that these two calls are equivalent:
import modname as mod
import modname as mod

I maintain a dictionary that maps (in this case) mod to modname. I use this not only to detect that modname has already been imported, but also for some other bookkeeping functions down the road.
Now, I can't detect that the following three calls import the same module:
import modname as mod
import modname as foo
import modname

I know that I can easily circumvent this problem by using a set to contain modname and check this set before I compile modname the second time. However, this requires another block of linear space.
I could do a linear pass over the dictionary to check if any key maps to a value of modname, but that defeats the purpose of using a dict.
Hence my question: does there exist a data structure that's a "two-way dict" - one that maps it's keys to values and whose values can be looked up at O(1) time as well?

A:

Python already tracks imported modules, in sys.modules.
Each key is a imported module name (and not the alias under which it was imported), each value is the actual module object with the global namespace for that module:
>>> import sys
>>> import os
>>> 'sys' in sys.modules
True
>>> 'os' in sys.modules
True
>>> sys.modules['sys'].__dict__.keys()
['setrecursionlimit', 'dont_write_bytecode', 'getrefcount', 'path_importer_cache', 'stdout', 'getprofile', '__stdin__', 'version_info', 'exc_clear', 'prefix', 'getfilesystemencoding', 'byteorder', '_clear_type_cache', 'excepthook', 'ps1', 'exc_type', '__excepthook__', 'executable', 'float_info', 'copyright', 'setdlopenflags', 'exec_prefix', 'getdlopenflags', 'getrecursionlimit', 'py3kwarning', 'path_hooks', '__package__', '_current_frames', 'platform', 'maxsize', 'version', 'exit', 'call_tracing', 'callstats', 'flags', 'setcheckinterval', '__doc__', 'api_version', '__plen', 'getdefaultencoding', 'getcheckinterval', 'maxunicode', 'settrace', 'setprofile', 'argv', '__stdout__', 'meta_path', '__name__', 'subversion', 'builtin_module_names', 'stdin', '__stderr__', '__egginsert', 'displayhook', 'ps2', 'gettrace', 'modules', 'warnoptions', 'last_type', 'getsizeof', 'last_traceback', 'maxint', '__displayhook__', '_getframe', 'stderr', 'exc_info', 'path', 'last_value', 'hexversion']