Q:

How to POST values with specific ID from page that displays a list?

I'm working on my first django project which is a sport betting app. My models are:
class Game(models.Model):
    home_team = models.CharField(max_length=100)
    away_team = models.CharField(max_length=100)

class GameBet(models.Model):
    gameid = models.ForeignKey(Game)
    bet = models.IntegerField(default=None) #values: 1(home win), 0 (draw), 2 (away win)
    userid = models.ForeignKey(User)

I am able to save user bets using a single game view, when I pass gameid in url, but that is not very effective.
I created a simple page with list of games with 1 form per game for a start (at the end I would prefer to send all bets with one button):
{% for game in games %}
{{ game.id }} | {{ game.home_team }} | {{ game.away_team }} | <form method="post"> {% csrf_token %} {{ form }}   <input type="submit" value="bet" /> </form>  <br>  {% endfor %}

and my form is:
if request.method == 'POST':
        #if request.POST["bet"] == 'bet':

        form = NewBetForm(request.POST)
        if form.is_valid():
            bet = form.save(commit=False)
            bet.gameid = [r.id for r in owing_games] #it gives me a list and ValueError Cannot assign "[10, 11, 12]": "GameBet.gameid" must be a "Game" instance.
            bet.userid_id = current_user.id
            bet.bet = form.value()
            bet.save()

How can I pass a single game.id in that case?
EDIT:
I think I can use request.POST.get(something) but I don't know how to pass my {{ game.id }} from template to views

A:

Create a hidden input field with value as game.id.
Example:
<input type='hidden' value='{{ game.id }}' name='game_id'>

Place the above html code within the form block. Now, you can access the value in the view as request.POST['game_id'].
And, if you want to place same bet for multiple game ids, then loop over game ids, retrieve the Game instance from database and assign each new GameBet instance gameid as the retrieved Game instance.
Single Game ID Example:
game_id = request.POST['game_id']
if request.method == 'POST':
    # rest of the code
    if form.is_valid():
        bet.game_id = Game.objects.get(id=game_id)

Multiple Game IDs Example:
game_ids = request.POST['game_ids']
if request.method == 'POST':
    for game_id in game_ids:
        bet = form.save(commit=False)
        bet.game_id = Game.objects.get(id=game_id)
        bet.save()
    # return response after loop


Q:

Has the padding on code blocks been increased?

Before

After

This isn't my eyes playing tricks on me, is it? I'm curious to know if the code block style has actually been changed, and if yes, why?

A:

This fixes an accessibility issue.
Depending on a system setting for scrollbars, the last line of <pre><code> blocks was blocked by the MacOS scrollbar in all browsers.

This has been reported on meta here, here, here, and here. It impacts a minority of folks for sure, but that still amounts to thousands of users having content blocked because of the way they prefer to view the web.
Since this is a system setting, we couldn’t find a reliable way to target only those people who were impacted. To further complicate things, we also discovered this bug was affected by whether or not a USB mouse was plugged in at the time.
So we increased the default padding to 12px (up from the existing 5px) for everyone. Initially we didn’t love adding extra spacing, but liked it after seeing it in action. The difference isn’t that excessive and it gives y’all a little more affordance to copy code blocks.
Although the root issue only impacts the bottom edge of code blocks, we’ve applied the same padding to all four sides. While we can’t reduce the vertical spacing any more, it’s a good point about the horizontal spacing and I’ve reduced it a bit. Here’s what that looks like:

This update will be live shortly, if it isn’t already.

Since we felt this improved the design AND fixed an OS-level bug allowing everyone to experience the same Stack Overflow, we pulled the trigger. We’ll monitor Mac OS updates to see if this issue is fixed by Apple.

A:

Noticed it, it seems a bit excessive to me.
Especially the left-side padding makes it seem like there's an extra empty column in front of each line, which can actually be meaningful in some cases. Also the top and bottom paddings start to take a lot of space in posts that have multiple short code blocks (which isn't all that uncommon in e.g. unix.SE, what with all the command line commands. For example, this one has a few of those, though not single-line ones. Another with a couple single-liners on SO.).
It also makes inline code blocks look reaally different from
real code blocks.

The new spacing does have the upside that a horizontal scroll bar fits better without covering the text. If you have one that appears as required, that is.
However, that has been discussed and adding extra space just for that purpose was status-declined just a while ago in Add some bottom padding to code snippets. With scrollbars set to always visible, the vertical padding really starts to add up.
I can see someone wanting to add some padding there, but can we tone it back down at least a bit?


Q:

Textarea value change when summernote div is changed

I have setup a div for the summernote to alter text pulled from a database.

<?php echo $laws['content']; ?>

$(document).ready(function() {
   $('#summernote').summernote({
     height: 300,
   });
});

directly following the div I have a text area with an ID.
<textarea id="lawsContent"></textarea>

I want the content of the textarea to change as I type in the summernote div. Just like what is happening while I am typing this question.

A:

Using the summernote API
I came up with this solution:
$(document).ready(function() {
    $('#summernote').summernote({
      onKeyup: function(e) {
        $("#lawsContent").val($("#summernote").code());
      },
      height: 300,
    });
});

A:

I think it is better to handle the onChange event.
v0.7.0
$('#summernote').summernote({
  callbacks: {
    onChange: function(contents, $editable) {
      console.log('onChange:', contents, $editable);
    }
  }
});

$(document).ready(function(){

    $("#summernote").summernote(
        {
            height: "10em",
            callbacks: {
              onChange: function (contents, $editable) {
                var code = $(this).summernote("code");
                $("#lawsContent").val(code);
              }
            }
        }
    );

});
#lawsContent
{
    width: 100%;
    height: 10em;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.min.css" rel="stylesheet"/>

Editor:

Output:
<textarea id="lawsContent" class="form-control"></textarea>

v0.6.5
As of this version, callback only works with camel case string.
$('#summernote').summernote({
  onChange: function(contents, $editable) {
    console.log('onChange:', contents, $editable);
  }
});

$(document).ready(function(){

    $("#summernote").summernote(
        {
            height: "10em",
            onChange: function (contents, $editable) {
                $("#lawsContent").val(contents);
            }
        }
    );

});
#lawsContent
{
    width: 100%;
    height: 10em;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.6.7/summernote.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

Editor:

Output:
<textarea id="lawsContent" class="form-control"></textarea>

A:

Inspired by @user3367639, this is a more generic way to do it
$('.summernote').each(function () {
    var $textArea = $(this);

    $textArea.summernote({
        onKeyup: function (e) {
            $textArea.val($(this).code());
            $textArea.change(); //To update any action binded on the control
        }
    });
});

And with this method :
String.prototype.strip = function()
{
   var tmpDiv = document.createElement("div");
   tmpDiv.innerHTML = this;
   return tmpDiv.textContent || tmpDiv.innerText || "";
}

You could do in your JS controller something like this to get the text value of your textarea
$myTextArea.val().strip(); //Where val() returns the html and strip() returns the text

Hope this will help


Q:

Android Development - Code for clicking one list view to another

I simply want to create a ListView containing "a","b","c".  When I click on each item, I want each item to direct a unique activity, each containing a different ListView.
Listview

A

1
2
3

B

3
4
5

C

6
7
8

Please provide the best code for this.  Its so hard to find something on here that does this.  Most entries are too specific for me to get a clear understanding of how to do all this in the most consistent, efficient manner.
Thanks in advance!

A:

If you want a ListView with A, B, C in one Activity and the sublists in another Activity, you really only need one generic ListActivity to handle this. You only have to pass the ListActivity different sets of data.
In the onCreate() below:

If the Activity is not passed special data it will display A, B, C and it will use the onListItemClick() method to start the sub-Activities.
If the Activity does have the extra data stored in the Intent, then it displays this extra data in the ListView and will ignore any calls to onListItemClick().

public class Example extends ListActivity {
    boolean isSubList = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] array;
        Intent received = getIntent();
        // Setup as main ListView
        if(received == null || !received.hasExtra("array")) {
            array = new String[] {"A", "B", "C"};
        }
        // Setup as sub ListView
        else {
            isSubList = true;
            array = received.getStringArrayExtra("array");
        }

        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        if(!isSubList) {
            Intent starting = new Intent(Example.this, Example.class);
            switch(position) {
            case 0:
                starting.putExtra("array", new String[] {"1", "2", "3"});
                break;
            case 1:
                starting.putExtra("array", new String[] {"4", "5", "6"});
                break;
            case 2:
                starting.putExtra("array", new String[] {"7", "8", "9"});
                break;
            }
            startActivity(starting);
        }
    }
}


Q:

Problem with link styling failures in ASP.NET MVC

I have an ASP.NET MVC application that has a jQuery Treeview and a jQuery Splitter in it.  There is a header at the top.  Below that, the splitter is used to separate the space into two divs.  The left div contains the treeview, and the right div contains the content.
I have a stylesheet just for the content area; all of the styling is prefixed with #Content, and the div that contains the content is id="Content".  Within that stylesheet, I have styled the <a> links so that they're not underlined unless you hover over them.
Typically I put a table in the content area to display some grid-style data.  Within the grid is a column of links to display detail.
Here is the problem.  Most of the links in the content area will work properly (they will underline when you hover over them), but there are one or two links in the column that are failing their a:link style; they will be underlined on first display, and stay underlined whether they are hovered over or not.
This only happens when the page is rendered out of the ASP.NET MVC application.  I am using the development web server in Visual Studio (Cassini) for testing.  If I View/Source in the browser, save the page on my desktop, and fixup the links to the jQuery scripts and the style sheets, and view the page in the browser by clicking on the thusly saved page, the problem does not occur.
I have tried both Internet Explorer 7 and the latest version of Firefox, and the links fail in exactly the same way, but only when running the actual application.  All of the styling works, except for <a:link> in the #Content div.
Has anyone seen these kind of random link styling failures before?  I am at a loss.  I don't understand why the page would work as advertised if I save it out of the browser and open it again, but it will not work from the application, regardless of browser.

A:

Fixed by adding a:visited { text-decoration:none } to the content area stylesheet, and clearing the browser cache.


Q:

Meaning of ついて when issued as a command?

I was watching a video of people in Japan getting yelled at and stopped by police, and several times I'd hear them yell「ついて！」.
I was unsure of the meaning, and after looking it up I couldn't figure out if it was 着いて e.g. "sit down" or 付いて e.g. "come here". I know that 付いて来て would mean something like "come with me", but I am not sure which one of these would be correct in that situation.
EDIT:
For clarity, it was a skateboarding video. Someone would do a trick on private property, and when the police/guards saw this happen they yelled「ついて！」, directed at the skateboarder.

A:

This is just a guess, but Japanese police/guards (and firefighters) would typically say

「どいて！」
  「ハイ、どいて」

to civilians and youngsters, like trespassing skateboarder(s).

「おまわりさん、どいて！」連呼する消防隊。 Fire fighter yelling cops, "Move off!"
  2012/09/11 -
  火災現場で部署しようとする位置に居た警察官へ、「おまわりさん、どいて！」と連呼するはしご車と、道路上の野次馬へマイクとサイレン、それに警笛で移動を促すポンプ車。 ( The fire fighters yelling to the cops about "get off from parking point". ) -- YouTube

What makes this video clip funny is that it's the policemen who are usually telling people 「どいて！」


Q:

When using a random parameter in a loop's qualifying comparison, does it call the randomization function once or each time the loops runs?

As per the question, let's say you have the following code:
    Random rand = new Random();
    for (int k = 0; k < rand.nextInt(10); k++) {
        //Do stuff here
    }

Does k get compared to rand.nextInt(10) only once, when the loop starts running, so that there's an equal chance of the loop running at every interval between 0 and 9? Or does it get compared each iteration of the loop, making it more likely for lower numbers to occur?
Furthermore, does this differ between languages? My example is for Java, but is there a standard that exists between most languages?

A:

Does k get compared to rand.nextInt(10) only once, when the loop starts running?

No, k is compared to the next random number the rand generates each time the loop continuation condition is checked.
If you wish to generate a random number once, define a variable, and set it to nextInt(10) before the loop. You could also use an alternative that counts backwards:
for (int k = rand.nextInt(10); k >= 0 ; k--) {
    //Do stuff here
}

The same is true in at least four other languages which use this syntax of the for loop - C++, C, C#, and Objective C.


Q:

How do I properly set up a spotlight cone?

I'm having a problem while rendering a searchlight-style spot lamp (i.e. I want to see the "light cone" in the final render ("Halo" option is checked), a.k.a. volumetric light).
It appears that the cone is not actually interrupted by other objects. Simplified example for illustration purposes:

point a spot lamp with a relatively narrow cone (e.g. 10° ) and "Halo" option enabled at the middle of a plane so that the spot is entirely on the plane.
render the whole setup from the side so you can see both sides of the plane
-> the spot's light cone will continue beyond the plane:

Is that a bug? If not, what would I have to do to stop the light cone from "penetrating" the plane? Note that the actual spot is only visible on the upper plane, not the bottom one. Also, if I place another object within the cone it will properly cast a shadow onto the next surface. It does not affect the "shape" of the light cone however, as I would expect...
I'm currently using Blender 2.69.8 Fastest Build from graphicall.org but also had this problem with the original 2.69 release.
(remainder of original text moved to new question: "Why do my spotlight's dimensions differ between rendered and non-rendered view?"

A:

In order for the spot lamp to be blocked by other objects, you must set the Step to at least 1:


Q:

Jackson Integral

Following an old post, I have tried to make a function that calculates the Jackson integral of $q$-calculus:
Clear[JacksonIntegral];
JacksonIntegral[f_[x_], q_, b_] := (1 - q) b Sum[q^j f[q^j b], {j, 0, ∞}]

When applied to
A[x_] := x^.25

I have no complaint but no evaluation. More generally, how could I make a new rule in Mathematica?

A:

Your code should work with a small tweak. You just need to use the name of the function instead and input the name of the function or a pure function:
jacksonIntegral[f_, q_, b_] := (1 - q) b Sum[q^j f[q^j b], {j, 0, ∞}]
a[x_] := x^.25
jacksonIntegral[a, 1/2, 0.1]
(* 0.0485152 *)
jacksonIntegral[#^0.25 &, 1/2, 0.1]
(* 0.0485152 *)

Alternatively,
Clear[jacksonIntegral]
SetAttributes[jacksonIntegral, HoldFirst];
jacksonIntegral[f_[x_], q_, b_] := (1 - q) b Sum[q^j f[x] /. x -> q^j b, {j, 0, \[Infinity]}]
a[x_] := x^.25
jacksonIntegral[a[x], 1/2, 0.1]
(* 0.0485152 *)


Q:

How to make forEach wait for subscribe to finish?

I'm using Angular 6 and my database is Firebase. Now I try to show each of the room's names according to its building. For example:
Building A
Room 1
Room 2
Building B
Room 1
Room 2

But every time I try, it will show all the building names first, and only then it will show the room's names. This is what I got for now:
Building A
Building B
Room 1
Room 2

I find out this happens because forEach keeps skipping the subscribe function.
I have attempted to use promise and await, but it doesn't work. Maybe because I use it in a wrong way? I'm not so sure how to use promise in a correct way.
async loadData(){
    this.navigationService.user
        .subscribe( user => {
        console.log(user);
        this.user = user;
        this.navigationService.getBuildings(this.user.orgId)
            .subscribe( building => {
            this.navMasterBuilding = [];
            this.buildings = building;
            this.buildings.forEach( async building2 => {
                this.completeBuildingId = building2.completeBuildingId;
                this.buildingName = building2.buildingName;
                console.log(building2.buildingName);
                await new Promise ((resolve, reject) => {
                    this.navigationService.getLocation(this.user.orgId, this.completeBuildingId)
                    .subscribe(location => {
                    console.log('room' + location);
                    this.navMasterLocation = [];
                    });
                    resolve();
                });
            });
        });
    });
}

I have try to delay it by using setTimeout, but it still does't work.

A:

Array.forEach only works with synchronous functions. Change it to using the for...of syntax which does work. Next to that you resolve the Promise before the call to getLocation has finished and the code in subscribe has ran. Change the code to call resolve within the getLocation.subscribe.
for(const building2 of buildings) {
    console.log(building2.buildingName);
    await new Promise ((resolve, reject) => {
        this.navigationService.getLocation(this.user.orgId, this.completeBuildingId)
            .subscribe(location => {
                console.log('room' + location);
                this.navMasterLocation = [];

                resolve();
             });
    });
}

Note that it can be simplified to:
for(const building2 of buildings) {
    console.log(building2.buildingName);
    const location = await this.navigationService.getLocation(this.user.orgId, this.completeBuildingId).toPromise();
    console.log('room' + location);
    this.navMasterLocation = [];
}

Also do note that I'm not quite sure why you use this.completeBuildingId instead of a local variable. Given that it gets overwritten in each iteration this seems a bit useless to me.


Q:

I requested accommodation & was terminated the next day. Now what?

I was working through a recruiter after being interviewed for a FED position (that's how they described it) for a shop where most programmers did at least some C# / full stack. During the interview, I clearly stated that I did not know C#, but had done (large amounts of) server-side Python and C, and would learn C# if desired.
I had intended to request a disability accommodation of 40 hours work per week, and yesterday my supervisor said that their chief client was mad and they wanted everybody to work "long hours." To quote a letter I sent the managing partner at my recruiter today:
I heard a bit more today. The team, in a meeting, acknowledged that management had asked for "more hours", and asked, "How much more?" And--this is the first time I've seen something like this happen--management refused to provide a number, saying, "If we say 10 hours, people will work ten hours and stop." (One of my colleagues said this was like saying, "Give me money," and when asked, "How much?" refused to give a number but just said, "Keep on giving me money and I'll tell you when it's enough.")
I explained that I had contacted my doctor for a formal letter of accommodation, and that there were serious health consequences possible for working that kind of hours. I also wrote,
Note: this is my own attempt to explain things, not simply a restatement of the laws:
My understanding of "reasonable accommodation" is modifying a change to a position (what would be asked by default) that will let an employee act and pursue a business's interests. Perhaps you've read Getting to Yes; I wrote a piece on interest-based negotiations in a friendly context at http://jonathanscorner.com/negotiation/ and talked about position-based and interest-based negotiations.
I would suggest that "work X many hours" is a position; productivity is an interest, and I talked during the phone call about what I could do to best serve [the client]'s interests. I have in the past been very productive with a 40 hour work week; "work overtime" is a position where "be productive" is an interest, and I am trying for friendly, win-win negotiation (I just told another programmer that I was available for comment on JavaScript development), where I can only succeed if my success includes seeing to my employer's success.
FWIW. This is largely personal opinion; a less opinion-based note is "Things go by a doctor's note."
This was after the managing partner read my original "I'm requesting accommodation" email to me, over the phone, word for word, at in a tone of voice I would consider the nonverbal equivalent of scare quotes, and said he was more or less clueless about what to do and asked who he should contact, e.g. the EEOC, to find out what to do with a request for accommodation. I stated that I didn't know but thought the EEOC would be good to contact, and said that usually people go by the doctor's note (I mentioned, wisely or not, one time where a boss tried to ran ramshod over my request for accommodation, and after I had said "40 hours is 40 hours," gave my work a severe indictment of professional incompetence until I pointed out that his requests were all either enhancements or a request to handle an ambiguity in the spec some other way, and then after that accused me of bad programming without ever volunteering a detail of what I'd done wrong, and then fired me).
That was this morning. This afternoon, he and the client's president announced that I was being termed, for cause, because I did not know C#. This much is of course true; I may have been using all unassigned time to read O'Reilly's "C# for experienced programmers in other languages" text, but I had been entirely transparent during the interview process and did not lead either recruiter or client to believe that I knew more C# than I in fact did.
What do I do from here?
And a related question: the contract stated that I owed two weeks notice, but the client did not know notice if I was termed for cause. Do I have any basis to say "I was transparent about my level of actual C# proficiency during the interview; not knowing C# is an excuse and you owe me two weeks' notice"?
Thanks,

A:

Under the circumstances as described, I would avoid dealing with this employer.
In times past federal government contractors made a habit of bidding on projects that included mandatory, and unpaid, overtime for salaried workers.  This eventually got the attention of Congress, and they put some limits on such procurements.  However, what those are is hard to tell from the links I've been able to find.
A keyword search on 'Federal Government Contract Mandatory Overtime' leads to this. All of the government documents that come back are massive - hundreds of pages. A number of attorneys have single page summaries.
In short, you're trying to work for an exploitative employer, and this is likely to get worse and worse. You had communications issues from day 1, and these won't stop. Therefore, the best thing to do is drop it and move on.
If you're in the Chicago area, Indeed.com is showing 1200 openings for C# programmers, and 800+ number for Python. There are lots of fish in that barrel.
The Wall Street Journal (among others) is full of horror stories about Illinois - political dysfunction and runaway taxation. Businesses in that part of the country may be in a jam, and this is what they have to do to survive. Employers in Indiana or Wisconsin might be able to afford you under the terms you're requesting.

A:

One reason companies hire people via agencies is to avoid typical HR hassles.  You are creating issues and hassles for the client -- limiting work hours, "requesting accommodation," sending long emails, bringing in doctor's notes.  The client company doesn't want to deal with any of that, they just want their work done.
The agency exists to protect the client company, not to accommodate you.  Your continued requests make it clear it's not a one-time exception.  You've brought this on yourself.
ps- you've heard of tl;dr?  I would suggest you consider that concept when composing emails to your future bosses, or questions to this site.  Not getting the concept is partly what got you fired.


Q:

Calculate closest gift position using javascript

I tried one practice and check the requirement below.
You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime
numbers and your house is at 0.
Given your current position find the closest gift to your position, and calculate the distance
between your current position and gift and tell the distance.
Ex:
For input 0, the output is 2
For number = 11, the output should be 0
For number = 2000000000, the output should be 11 For number = 1800000001, the output
should be 10
For the above logic I tried to use javascript and almost I have completed but i'm not getting the proper outpu as per the requirement,my output is returning any number.
Javascript
function isPrime(num) {
    if (num <= 1) {
        return false;
    } else if (num <= 3) {
        return true
    } else if (num % 2 === 0 || num % 3 === 0) {
        return false
    }

    let i = 5
    while (i * i <= num) {
        if (num % i === 0 || num % (i + 2) === 0) {
            return false
        }
        i += 6
    }
    return true
}

HTML

 Gift House

    Enter a house Number
    <input type="text" id="inp" class="clr" />
    <input type="button" id="checker" value="Calculate" onClick="findpos()">
     Distance of the gift house
    <input type="text" id="demo" value="" class="clr">

A:

I understood your requirement,you have tried 2 steps properly but before those two steps you have to do one more logic to calculate prime number.Because you have called the function isPrime in your JS but where you defined the function?
Just include the below script in your JS code and check the output.
function findpos() {
    var num = document.getElementById("inp").value;
    var pos = 0;
    while (true) {
        if (isPrime(num)) {
            break;
        } else {
            pos++;
            num++;
        }
    }
    document.getElementById("demo").value = pos;
}


Q:

How to Find/replace with Regular Expressions and Wildcards in Notepad++

I need some help identifying a find/replace regular expression I could use to find a string of data that has two dates between pipes and replace the first date with a new date in Notepad++. I've done some research, but don't follow how this could be done. Last resort, I'll manually replace them all, but that isn't ideal.
Each row on the file has other information before and after the date section specified below; however, I expect that could be ignored since we're only wanting to use find/replace for the dates.
Here's 3 lines that may exist on the file.
|05/28/2016|12/31/2050|
|04/13/2014|12/31/2050|
|12/17/2013|12/31/2050|

I'm looking for an expression that would allow me to find/replace the first date within the first set of pipes with an alternative date I specify.
Find this...
|Wildcard Section|12/31/2050|

Replace with this...
|6/1/2016/12/31/2050|

Can this be done?
Thanks,
Brandon

A:

As long as 6/1/2016 doesnt change or is not a variable you can do something like this
On Find what: field add (.*)(\d{2}/\d{2}/\d{4})(\|\d{2}/\d{2}/\d{4}.*)
On Replace with: field add ($1)6/1/2016($3)
On the top regex we break the match to 3 part (they are stored in $1, $2 and $3 respectively) for each section we need. We need to replace the middle date, $2 above replace statement will do the job.
find/replace window configuration screenshot:
http://prntscr.com/bjcnf8


Q:

Rails 3, :json => @model.to_json OR :json => @model

I just wandered the difference between:
format.json { render :json => @post, :include => [ :user ] }

...and
format.json { render :json => @post.to_json(:include => [ :user ]) }

They both seem to work?

A:

it's the same. if you have a look at actionpack renderers.rb you will see how it works:
add :json do |json, options|
  json = json.to_json(options) unless json.kind_of?(String)
  json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
  self.content_type ||= Mime::JSON
  json
end


Q:

How to solve the limit for power tending to infinity

How does one find
$$
\lim_{x \to 0} \left[1 + x\sin(\pi - x) \right]^{1/x}\ ?
$$
Does the limit exist? If yes, how is it found?

A:

hint
$$f (x)=e^{\frac {1}{x}\ln (1+x\sin (x))}$$
but $$\ln (1+x\sin (x))\sim x^2 \;\;(x\to 0)$$
thus your limit is $e^0=1$.
or
$$f (x)=e^{ \sin (x)\frac {\ln (1+x\sin (x))}{x\sin (x)}}$$
and $$\lim_{X\to 0}\frac { \ln (1+X) }{  X}=1$$


Q:

ensuring a well-defined object state when a constructor throws an exception

I have a Visual Studio 2008 C# .NET 2.0CF application. I'm using a component base from which two concrete components are derived. The application first attempts to use SomeDisposableComponent. Its constructor throws an exception because it requires a feature that isn't available. Then, the application tries SomeOtherDisposableComponent. Its construction succeeds.
The problem is that the first component's constructor already added itself to the form's container of components before the exception was thrown. So, when the form is disposed the first component's Dispose() member is called even though the object was never fully constructed. That causes problems for the second component's destructor.
How can I ensure that when the first component throws an exception on construction, the references to it are removed?
public abstract class SomeDisposableComponentBase : Component
{
    private System.ComponentModel.IContainer components;

    private SomeInternalDisposable s_ = new SomeInternalDisposable();

    protected SomeDisposableComponentBase()
    {
        Initializecomponent();
    }

    protected SomeDisposableComponentBase(IContainer container)
    {
        container.Add(this);
        Initializecomponent();
    }

    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
    }

    protected abstract void Foo();

    #region IDisposable Members
    bool disposed_;

    protected override void Dispose(bool disposing)
    {
        // called twice. the first time for the component that failed to initialize properly.
        // the second for the one that was used.
        if (!disposed_)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            // on the second call, this throws an exception because it is already disposed.
            s_.Close();
            disposed_ = true;
        }
        base.Dispose(disposing);
    }
    #endregion
}

public SomeDisposableComponent : SomeDisposableComponentBase
{
    public SomeDisposableComponent() : base()
    {
    }

    public SomeDisposableComponent(IContainer container) : base(container)
    {
        // This will throw an exception if it requires a feature that isn't available.
        SomeInitFunction();
    }

    protected override void Foo()
    {
        // Do something...
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

public partial class my_form : Form
{
    private SomeDisposableComponentBase d_;

    public my_form()
    {
        InitializeComponent();
        if (null == components)
            components = new System.ComponentModel.Container();

        try
        {
            // try the default component
            d_ = new SomeDisposableComponent(components);
        }
        catch (System.Exception)
        {
            try
            {
                // the default component requires some feature that isn't available. Try a
                // backup component.
                d_ = new SomeOtherDisposableComponent(components);
            }
            catch (System.Exception e)
            {
                // display error to the user if no suitable component can be found.
            }
        }
    }

    /// exit button clicked
    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    /// from the my_form.designer.cs
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            // this function is executed as expected when the form is closed
            components.Dispose();
        }
        base.Dispose(disposing);
    }
}

Thanks,
PaulH

Edit: Removed unused code
The container within the SomeDisposableComponentBase was confusing. It's not relevant to the issue and I should have removed it earlier.
public abstract class SomeDisposableComponentBase : Component
{
    private SomeInternalDisposable s_ = new SomeInternalDisposable();

    protected SomeDisposableComponentBase()
    {
    }

    protected SomeDisposableComponentBase(IContainer container)
    {
        container.Add(this);
    }

    protected abstract void Foo();

    #region IDisposable Members
    bool disposed_;

    protected override void Dispose(bool disposing)
    {
        // called twice. the first time for the component that failed to initialize properly.
        // the second for the one that was used.
        if (!disposed_)
        {
            if (disposing)
            {
                // on the second call, this throws an exception because it is already disposed.
                s_.Close();
            }
            disposed_ = true;
        }
        base.Dispose(disposing);
    }
    #endregion
}

public SomeDisposableComponent : SomeDisposableComponentBase
{
    public SomeDisposableComponent() : base()
    {
    }

    public SomeDisposableComponent(IContainer container) : base(container)
    {
        // This will throw an exception if it requires a feature that isn't available.
        SomeInitFunction();
    }

    protected override void Foo()
    {
        // Do something...
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

public partial class my_form : Form
{
    private SomeDisposableComponentBase d_;

    public my_form()
    {
        InitializeComponent();
        if (null == components)
            components = new System.ComponentModel.Container();

        try
        {
            // try the default component
            d_ = new SomeDisposableComponent(components);
        }
        catch (System.Exception)
        {
            try
            {
                // the default component requires some feature that isn't available. Try a
                // backup component.
                d_ = new SomeOtherDisposableComponent(components);
            }
            catch (System.Exception e)
            {
                // display error to the user if no suitable component can be found.
            }
        }
    }

    /// exit button clicked
    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    /// from the my_form.designer.cs
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            // this function is executed as expected when the form is closed
            components.Dispose();
        }
        base.Dispose(disposing);
    }
}

A:

Your form should be in charge of adding items to its components collection -  not the components you're adding to the collection. Doing it inside the added components makes it extremely difficult to reason about what's happening in your form.
// It is not obvious that the component is adding itself to the list
new SomeDisposableComponent(components);

// Instead, be explicit where it matters
Component someDisposableComponent = new SomeDisposableComponent(components);
this.components.Add(someDisposableComponent);

Next, to solve your constructor problem, you should move the logic out of the constructor. This is generally good practice - people do not expect constructors to have side effects, and logic in your constructors makes classes difficult to test. If you want to guarantee that something happens every time you create an instance, create a factory and make it so the factory is the only way to get an instance of your class (make the class' constructor internal, or use some other technique):
public class SomeDisposableComponentFactory {
    public SomeDisposableComponent CreateInstance() {
        SomeDisposableComponent component = new SomeDisposableComponent();
        component.SomeInitFunction();
    }
}

Finally, you should consider moving the logic for selecting and creating components out of your form and into a general component factory:
public class ComponentFactory {

    // The input parameter can be whatever you need to choose the right component
    public Component CreateInstance(object input) {

        if (input == something) {
            SomeDisposableComponent component = new SomeDisposableComponent();
            component.SomeInitFunction();
            return component;
        }
        else {
            return new AnotherComponent();
        }
    }
}


Q:

Python Loggly logging setup using dictconfig

I want to try Loggly in my new PaaS python app, as I usually code against a linux server and just use the standard rotating file handler. This presents an issue as their documented configuration only covers using a .conf file and as they have a few custom methods in their preferred HTTPS handler there's a couple of tricks to configuring it any other way.
I have been using nested .py files to handle the config for the rest of my application and didn't want to change, and it looked like the dictconfig method was preferred in the documentation.
So, how to resolve this?

A:

This approach uses the dictconfig method of the standard python logging module, and was tested on 2.7.9
Install the 'loggly-python-handler' module.
In your code, you could do the following where 'conf' is your .py config file:
import logging, logging.config
import loggly.handlers
import conf

# Init Logging
logging.config.dictConfig(conf.LOGGING)
logger = logging.getLogger(u'root')

Then, in the 'conf.py' file, you could use the following dictionary (replace your key):
LOGGING = {
    u'version': 1,
    u'handlers': {
        u'loggly': {
            u'class': u'loggly.handlers.HTTPSHandler',
            u'formatter': u'basic',
            u'level': u'DEBUG',
            u'url': u'https://logs-01.loggly.com/inputs/YOUR_KEY_HERE/tag/pytest'
        },
        u'console': {
            u'class': u'logging.StreamHandler',
            u'level': u'DEBUG',
            u'formatter': u'basic',
            u'stream': u'ext://sys.stdout',
        }
    },
    u'formatters': {
        u'basic': {
            u'format': u'%(asctime)s | %(name)15s:%(lineno)3s:%(funcName)15s | %(levelname)7s | %(message)s'
        }
    },
    u'loggers': {
        u'root': {
            u'level': u'DEBUG',
            u'handlers': [u'console', u'loggly']
        }
    }
}

This is a combination of instructions for using dictconfig from the logging module documentation: https://docs.python.org/2/library/logging.config.html
And digging through the code of the 'loggly-python-handler' module to see how its constructor worked :https://github.com/psquickitjayant/loggly-python-handler/blob/master/loggly/handlers.py
You could also test this directly from the console with (don't forget to add your key):
import logging
import loggly.handlers
handler = loggly.handlers.HTTPSHandler(url='https://logs-01.loggly.com/inputs/YOUR_KEY_HERE/tag/python')
logger = logging.getLogger(u'root')
logger.addHandler(handler)
logger.warning("test loggly connection")


Q:

DNSSEC - How many DS records are ordinary?

I thought that I need two DS records to deposit at my domain registrar. But one big dns provider just gave me one DS record. Verisign DNSSEC debugger says, everything is correct. But I am confused, because dnssec-keygen (DNSSEC key generation tool) gave me always two DS records. I have my doubts.

A:

When you get 2 DS records, it is basically always because one of them contains a SHA-1 hash and the other one contains a SHA-256 hash. Look at the third integer in the textual representation of the DS record. 1 means SHA-1 and 2 means SHA-256.
If both types exist, verifiers may use whichever one they like, though they should use the strongest one they understand. That means verifiers will use SHA-256 if they support it, or SHA-1 otherwise.
The SHA-1 version of the DS record need only be present to support older verifiers that do not understand SHA-256. Hopefully such verifiers are vanishingly rare, so you should be fine with just a SHA-256 DS record.
If you were giving only a SHA-1 record and no SHA-256 record, you should ideally ask for a SHA-256 one, but don't worry about it too much: for now SHA-1 is probably still acceptable.


Q:

Variable length register slices in Verilog

I need to concatenate a register, and a variable-length part of another. I have register offset which counts how many bits of the variable-length register I need.
I would like to do something like this:
A <= {B[offset:0], A};
However, this is a compilation error.
I could write a mux that chooses different assignment for A, for different values of offset: i.e:
if (offset == 1)
   A <= {B[1:0], A};
else if (offset == 2)
   A <= {B[2:0], A};

etc. This is cumbersome, ugly and not extensible for new values of offset. Are there any better ideas?
Thank you

A:

Use a mask
A <= { B & (2**(offset+1)-1)}

Note that in your example, A<= {whatever,A} will always be just A.


Q:

Why need conventional Hibernate?

As far as I know Hibernate has two types of implementations

implementation of JPA (2)(@Entity,@Table annotations)
extension to older(conventional) hibernate (without JPA) ,HSQL queries are used, there is not annotation

If it is true, Why do we need second type of implementation while JPA is the ORM specification?
If you can give API version while comparing them it could be better for me to understand the whole evaluation history of ORM?
Thanks.

A:

Hibernate was one of the first ORM tools, before the JPA specification.  It was also developer before Java 5 (when annotations became available in Java), so everything used to be either XML configuration based, or XDoclet.
There was a big revamp of Java EE , which borrowed heavily from Spring and Hibernate, that introduced JPA but was also "generic" enough that you could plug in your own implementations.
There's no real difference in how hibernate works, just what mechanism you use to configure it.  JPA annotations is now the standard, but you can still use XML only if you want.


Q:

Sense HAT set_pixels TypeError: object of type 'int' has no len()

I have been writing a competition entry, trying to make an mp3 player with the Raspberry Pi Sense HAT. I have added a play function with pygame.mixer.music and I want to have patterns to display on the screen (randomly generated from a selection), but when I run my program, I only get this error:
Traceback (most recent call last):
  File "/home/pi/Astro Pi/MP3 Player/player.py", line 90, in <module>
    display()
  File "/home/pi/Astro Pi/MP3 Player/player.py", line 65, in display
    sense.set_pixels(pattern_one)
  File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 268, in set_pixels
    if len(pix) != 3:
TypeError: object of type 'int' has no len()

Can you help? Here is my full code...
#! /usr/bin/env python
# Import the SenseHAT libraries and set them up for easy access
from sense_hat import SenseHat
sense = SenseHat()
# Import the other libraries I need for the MP3 player
import time, os, pygame.mixer, random, glob
# Make sure that the music will play out of the Audio Jack socket
def display():
    colors = [[178,31,53],[216,39,53],[255,116,53],[255,161,53],[255,203,53],[255,249,53],[0,117,58],[0,158,71],[22,221,52],[0,82,165],[0,121,231],[0,169,252],[104,30,126],[125,60,181],[189,122,246]]
    a = random.choice(colors)
    b = random.choice(colors)
    c = random.choice(colors)
    choice = random.randint(1,5)
    pattern_one = [
        a,0,0,b,b,0,0,a,
        0,a,0,b,b,0,a,0,
        0,0,a,b,b,a,0,0,
        b,b,b,a,a,b,b,b,
        b,b,b,a,a,b,b,b,
        0,0,a,b,b,a,0,0,
        0,a,0,b,b,0,a,0,
        a,0,0,b,b,0,0,a
        ]
    pattern_two = [
        a,b,a,b,a,b,a,b,
        b,a,b,a,b,a,b,a,
        a,b,a,b,a,b,a,b,
        b,a,b,a,b,a,b,a,
        a,b,a,b,a,b,a,b,
        b,a,b,a,b,a,b,a,
        a,b,a,b,a,b,a,b,
        b,a,b,a,b,a,b,a
        ]
    pattern_three = [
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b,
        a,b,a,b,a,b,a,b
        ]
    pattern_four = [
        a,a,a,a,a,a,a,a,
        b,b,b,b,b,b,b,b,
        a,a,a,a,a,a,a,a,
        b,b,b,b,b,b,b,b,
        a,a,a,a,a,a,a,a,
        b,b,b,b,b,b,b,b,
        a,a,a,a,a,a,a,a,
        b,b,b,b,b,b,b,b,
        ]
    pattern_five = [
        a,a,b,b,b,b,a,a,
        a,a,b,b,b,b,a,a,
        a,a,c,c,c,c,a,a,
        a,a,c,c,c,c,a,a,
        a,a,b,b,b,b,a,a,
        a,a,b,b,b,b,a,a,
        a,a,c,c,c,c,a,a,
        a,a,c,c,c,c,a,a
        ]
    if choice == 1:
        sense.set_pixels(pattern_one)
    elif choice == 2:
        sense.set_pixels(pattern_two)
    elif choice == 3:
        sense.set_pixels(pattern_three)
    elif choice == 4:
        sense.set_pixels(pattern_four)
    elif choice == 5:
        sense.set_pixels(pattern_five)
    time.sleep(0.2)
    sense.clear()
os.system("sudo amixer cset numid=3 1")
# Make sure that the volume is turned up so that pygame can control it
os.system("sudo amixer cset numid=1 100%")
# Initialise pygame
pygame.mixer.init()
# Look for all the .mp3 files in the 'songs' folder and put their file names in a list
songs = glob.glob('songs/' + '*.mp3')
# Choose a random file from the list and load it up to start with
pygame.mixer.music.load(random.choice(songs))
# Make sure the volume is up to 100%
pygame.mixer.music.set_volume(1.0)
# Play the song
pygame.mixer.music.play()
while True:
    display()

A:

I think that's because you are using zeroes in your pattern matrices, RGB lists are needed instead. Try to set those zeros to some color (i guess black) like in this reference:
https://pythonhosted.org/sense-hat/api/#set_pixels
from sense_hat import SenseHat

sense = SenseHat()

X = [255, 0, 0]  # Red
O = [255, 255, 255]  # White

question_mark = [
O, O, O, X, X, O, O, O,
O, O, X, O, O, X, O, O,
O, O, O, O, O, X, O, O,
O, O, O, O, X, O, O, O,
O, O, O, X, O, O, O, O,
O, O, O, X, O, O, O, O,
O, O, O, O, O, O, O, O,
O, O, O, X, O, O, O, O
]

sense.set_pixels(question_mark)


Q:

System connected to UPS goes to sleep short time after power is lost

I have a Win7 x64 system connected to the UPS. The UPS is capable of maintaining the system power for about 30 minutes. After I have connected the UPS, I have verified this by disconnecting the power cord and everything has worked as expected, I was receiving low level battery notifications and the system went off once the battery has reached the critical level. Since then a long time passed. Recently I was experiencing a power loss several times, and each time the computer went to sleep in a very short time.
I can reproduce this easily any time by disconnecting the power cord from the UPS. When I do this, the system correctly shows the battery level and the remaining battery time when I disconnect the cord (the level starts at 100% and the remaining time at 0:32 and gradually goes down). Yet, the system sleeps after a short while without any warning.
I do not have any 3rd party software installed to manage the UPS, I am using default Windows battery handling. My advanced power settings when on battery are as follows:

Sleep after: 20 Minutes
Critical battery action: Sleep
Low battery level: 20%
Critical battery level: 10%
Low battery notification: On
Low battery action: Do nothing
Reserve battery level: 7%

When the system sleeps, following entry is shown in the event log:
The system is entering sleep. Sleep Reason: Battery
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
  <Provider Name="Microsoft-Windows-Kernel-Power" Guid="{331C3B3A-2005-44C2-AC5E-77220C37D6B4}" />
  <EventID>42</EventID>
  <Version>2</Version>
  <Level>4</Level>
  <Task>64</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8000000000000004</Keywords>
  <TimeCreated SystemTime="2012-08-01T06:55:18.358031800Z" />
  <EventRecordID>325242</EventRecordID>
  <Correlation />
  <Execution ProcessID="4" ThreadID="48" />
  <Channel>System</Channel>
  <Computer>xxxxx</Computer>
  <Security />
</System>
<EventData>
  <Data Name="TargetState">4</Data>
  <Data Name="EffectiveState">4</Data>
  <Data Name="Reason">2</Data>
  <Data Name="Flags">0</Data>
  </EventData>
</Event>

I have found a user reporting and solving a similar problem on Microsoft Answers, in his case the cause were broken drivers for Iomega drive. While I have quite a lot of devices connected to the computer, I do not have any Iomage drive.

Is there any systematic way how could I troubleshoot this problem or identify which particular device is malfunctioning and causing the computer to sleep?
Does some documentation for "Microsoft-Windows-Kernel-Power", which would help me understand the exact source of the event?

A:

I was not able to solve the issue despite of my efforts. I was not even able to get any more information on the "Microsoft-Windows-Kernel-Power" so far.
The best I could do was a workaround: instead of using native Windows battery management I have installed APCUPSD software and I can no longer observer the issue. With this sotware Windows are not aware of the battery, the APCUPSD controls shutdown directly and I have verified it is not doing so prematurely.
I guess using APC provided PowerChute might work as well, but I did not like the sofware much when I installed it, sounds too much cluttered and obtrusive to me.


Q:

where to put hashkey into facebook developers page?

I am currently developing an application for android with using facebook API. But even though I create an app on facebook and insert it's app_id into my code, I get this message when I try to log in to facebook:
"This app has no android key hashes configured, configure your app key hashes at http://developers.facebook.com/apps/1232412xxxxxxxx"
I followed this guide :
https://developers.facebook.com/docs/android/getting-started/
and get hash key, but I couldn't find what to do with this hash key?

A:

I found the answer,

I coppied my hashkey.
Navigated to https://developers.facebook.com/apps/
Selected my app
Selected "Native Android App" under "Select how your app integrates with Facebook"

Here was the answer.


Q:

Why Ubuntu do not run video games? or some programs i used to run on windows 7

I cannot run video games I used to play in Windows 7, also there are a lot of programs that worked on Windows 7 but don't work on Ubuntu

A:

Ubuntu is an open sourced (free as in free beer and free speach) operating system built on the Debian Linux kernel.  Windows is built on the Microsoft proprietary NT kernel.  The methods of programming are different for the separate kernels.  This is a very basic description of why the programs are not usually cross compatible.
There is light at the end of the tunnel.  You can attempt to use WINE which translates in the backend for you.  You can read more on that on this site:
http://www.winehq.org/


Q:

Hackerrank "Sherlock Holmes" challenge

Watson gives to Sherlock an array: A1, A2, ⋯, AN. He also gives to
  Sherlock two other arrays: B1, B2, ⋯, BM and C1, C2, ⋯, CM. Then Watson asks
  Sherlock to perform the following program:
  for i = 1 to M do
   for j = 1 to N do
     if j % B[i] == 0 then
         A[j] = A[j] * C[i]
    endif
 end do
end do

Can you help Sherlock and tell him the resulting array A? You should print all the array elements modulo (1000000007).
Input Format
The first line contains two integer numbers N and M. The
  next line contains N integers, the elements of array A. The next two
  lines contains M integers each, the elements of array B and C.
Output Format
Print N integers, the elements of array A after
  performing the program modulo (1000000007).
Sample Input
4 3
1 2 3 4
1 2 3
13 29 71

Sample Output
13 754 2769 1508

If we brute force, it will time out.  Please suggest ways on making this efficient.
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;

public class SherlockArray {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String line1 = in.nextLine();
    StringTokenizer st = new StringTokenizer(line1, " ");

    int n = Integer.parseInt(st.nextToken());
    int m = Integer.parseInt(st.nextToken());
    Long[] b = new Long[m];

    String strA = in.nextLine();
    String[] stA = strA.split(" ");
    BigInteger aBI[] = new BigInteger[n];
    for (int ia = 0; ia < stA.length; ia++) {
        aBI[ia] = new BigInteger(stA[ia]);
    }

    String strB = in.nextLine();
    String[] stB = strB.split(" ");
    for (int ib = 0; ib < stB.length; ib++) {
        b[ib] = Long.parseLong(stB[ib]);
    }

    String strC = in.nextLine();
    String[] st3 = strC.split(" ");
    for (int ic = 0; ic < m; ic++) {
        for (int index = b[ic].intValue(); index <= n; index += b[ic]
                .intValue()) {
            aBI[index - 1] = aBI[index - 1].multiply(new BigInteger(st3[ic]));
        }
    }

    for (int ia = 0; ia < n; ia++) {
        aBI[ia] = aBI[ia].mod(new BigInteger("1000000007"));
        System.out.print(aBI[ia] + " ");
    }

}

}

A:

In 1801, a guy called Carl Friedrich Gauss studied problems where the number line wrapped around, called Modular Arithmetic.
In his studies, he proved that:
$$
    (a \times b)\ \%\ n = [(a)\ \%\ n \times (b)\ \%\ n]\ \%\ n
$$
Also, 1000000007 is a prime number which means that there are other benefits...
And, it is also just less than half of Integer.MAX_VALUE.
Finally, two int values, no matter how large, when multiplied, will never be larger than Long.MAX_VALUE
Putting this all together, you can rewrite your code without the BigInteger math, something like:
for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
        if (j % B[i] == 0) {
            A[j] = (int)( ( (long) A[j] * C[i]) % 1000000007L);
        }
    }
}
System.out.println(Arrays.toString(A));

So, using some math, you can avoid the BigInteger problem entirely, and keep things as long and int values.
I imagine that this will be enough of a performance improvement to avoid the timeout.
Note, that for large numbers, BigInteger has \$O(s)\$ type complexity where s is the magnitude of the number, when doing multiplication. The bigger the number, the slower the product. Thus, your complexity for your current solution is \$O(nms)\$ where n is the size of the A array, m is the size of the B and C arrays, and s is the average size of the BigIntegers used. By reducing the problem to int-size values, we reduce the time complexity by a full order to just\$O(nm)\$.
There are likely ways for you to be able to solve the math in O(n) time as well.... I just need to think about how to restructure the if condition in the loops

A:

The original post used 1-based arrays.  If you change them to 0-based, you should test (j+1)%B[i] == 0, not j%B[i] == 0.
for (int j = 0; j < M; j++) {
    if ((j+1) % B[i] == 0) {
        ...
    }
}

And that can be rewritten:
for (int j = B[i]-1; j < M; j+=B[i]) {
    ...
}

It can be faster depending how large the B[i] are.

A:

A far more optimal solution involves keeping track of the number of times that B[i] occurs.
This is because for every multiple of B[i]: B[i], 2 * B[i], ..., j * B[i], we multiply A[i * j] by C[i]
This yields the following info for the example:
1 occurs 4 times (4 multiples), 2 occurs 2 times (2 multiples), 3 occurs 1 time (3 multiples), 4 occurs 1 time (1 multiple)
Therefore, we multiply 1 by 13, 2 by 13, 3 by 13, 4 by 13 (first 4 multiples of 1)
we multiply 2 by 29, 4 by 29 (first 2 multiples of 2)
we multiply 3 by 71 (first multiple of 3)
we multiply 4 by 1 (since C[4] doesn't exist)
This yields a net result of multiplying 1 by 13, 2 by 13 * 29, 3 by 13 * 71, 4 by 13 * 29
This approach ends up being \$O(N * log(N))\$ because for each N, you do N/i multiplications, meaning you do a total of:
N/1 + N/2 + N/3 + N/4 + ... N/N = N * (1/1 + 1/2 + 1/3 + ... + 1/N) = O(Nlog(N)),

since (1/1 + 1/2 + 1/3 + ...) is the harmonic series and grows with \$O(log(N))\$
Here is the relevant code, which produced the results in under 2 seconds, mostly due to very inefficient I/O. I changed BigIntegers to Longs, as BigIntegers are very SLOW in Java. I also repeatedly used modulo multiplication. These two suggestions were brought up by rofl, but I wanted to re-iterate them.
import java.io.*;
import java.util.*;

public class Solution {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       Long N = scanner.nextLong();
       Long M = scanner.nextLong();
       scanner.nextLine();

       ArrayList<Long> A = new ArrayList<Long>();
       ArrayList<Long> B = new ArrayList<Long>();
       ArrayList<Long> C = new ArrayList<Long>();

       A.add(0L);
       for (String string : scanner.nextLine().split(" ")) {
           A.add(new Long(string));
       }
       B.add(0L);
       for (String string : scanner.nextLine().split(" ")) {
           B.add(new Long(string));
       }
       C.add(0L);
       for (String string : scanner.nextLine().split(" ")) {
           C.add(new Long(string));
       }

       HashMap<Long, Long> counts = new HashMap<Long, Long>();

       for (int i = 1; i < M+1; i++) {
           if (counts.containsKey(B.get(i))) {
               counts.put(B.get(i), (counts.get(B.get(i)) * C.get(i)) % 1000000007L);
           }
           else {
               counts.put(B.get(i), C.get(i));
           }
       }

       for (Long i = 1L; i < N+1; i++) {
           for (Long j = 1L; j < (N / i) + 1L; j++) {
               if (counts.containsKey(i)) {
                   A.set((int)(i * j), (A.get((int)(i * j)) * counts.get(i)) % 1000000007L);
               }
           }
       }

       System.out.print(A.get(1));
       for (int i = 2; i < A.size(); i++) {
           System.out.print(" " + A.get(i));
       }
    }
}


Q:

i'm unable to understand how this code works

This is a c program to find out all possible combinations with a word -->
# include <stdio.h>

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
     printf("%s\n", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
   char a[] = "ABC";
   permute(a, 0, 2);
   getchar();
   return 0;
}

can anyone please explain me how the permutation code part is working? thanks in advance

A:

Perhaps you have problem understanding the backtrack technique. In this case you should read a little about it: http://en.wikipedia.org/wiki/Backtracking
However the code works from the char at position 0 up to 2 following chars.
It changes the first char with the folowing, and calls itself with the next char as starting point. Finally switch back the chars to recreate the orign situation.
At the first level of recursion the function is switching the first letter and call itself for the next two:
permute("ABC", 1, 2)
permute("BAC", 1, 2)
permute("CBA", 1, 2)

second level of recursion:
permute("ABC", 2, 2) /* -> printf ABC */
permute("ACB", 2, 2) /* -> printf ACB */

permute("BAC", 2, 2) /* -> printf BAC */
permute("BCA", 2, 2) /* -> printf BCA */

permute("CBA", 2, 2) /* -> printf CBA */
permute("CAB", 2, 2) /* -> printf CAB */


Q:

How can there be an inner product space when inner product yields a scalar?

I thought the inner product yields a scalar in both real and complex cases. How can a space be made up of scalars? Taking two vectors $a$ and $b$, $a=(a_1,a_2)$ and $b=(b_1,b_2)$, the inner product is $$( a,b)=(a_1\overline{b_1}+a_2\overline{b_2})$$
That's a scalar. How can there be a space of scalars?

A:

An inner product space is a linear space, equipped with an inner product on it. So, it's a pair $(X,\langle\cdot,\cdot\rangle)$, where $X$ is the linear space and $\langle\cdot,\cdot\rangle$ the inner product on $X$.


Q:

iphone SDK: View generate without IB spacing problem

I generate a ViewController / View in my window based application.
It will show directly at startup, it works, no problem.
But on the buttom, the View has Space left, its exactly the space the status bar needs on the top, so I think I must put my View under the status bar, not behind it.
How to do?
Code:
StartViewController *a = [[StartViewController alloc] initWithNibName:@"bla"];
[self setStartViewController:a];
[a release];
[window addSubviewl:[StartViewController view]];

A:

It is either not high enough, or your upper left corner doesn't account for the statusbar, i.e. (0,20).


Q:

Table border-bottom at rows

I try to put a border-bottom at the table-rows but they don't show up. Why is that?
http://www.mysecretathens.gr/Sera/dates.html
I think my code is pretty simple putting a class to ther tr element.
<tr class="line">

table tr.line {border-bottom: 1px solid #B4B5B0;}

A:

You can try this:
tr.line td{
border-bottom: 1px solid #B4B5B0;
}


Q:

Type casting and inspection query

I am currently working through the basics of Type Casting and Inspection in swift 4.  I have found an example in the Apple Developer book which i need a bit of help with.
They have an exercise to create an Any type dictionary and then unwrap the values looping through the dictionary. The given solution shows the for loop with the value in brackets and each value being unwrapped. Can someone give an explanation for the solution shown? and is there another(simple) way to solve this? There is not enough information in the book.
let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]

print(anythingAndEverything)

var total: Double = 0
for (_, value) in anythingAndEverything {
    if let value = value as? Bool {
        if value {
            total += 2
        } else {
            total -= 3
        }
    } else if let value = value as? Double {
        total += value
    } else if let value = value as? Int {
        total += Double(value)
    } else if let value = value as? String {
        total += 1
    }
}

print(total)

Many thanks for any help in advance :-)

A:

Dictionary conforms to Collection, which conforms to Sequence. This means that a dictionary can be looped through using a for...in loop.
In the definition of Dictionary, there is this line:
public typealias Element = (key: Key, value: Value)

This means that "in the collection called a dictionary, it contains elements of type (key: Key, value: Value)". This means that you will get (key: Key, value: Value) as the type of the variable before in:
for element in someDictionary {
    // element is of type (key: Key, value: Value)
}

Since element is a tuple, we can actually unwrap the tuple by doing this:
for (key, value) in someDictionary {}

In your specific situation, we don't need the key bit, so we write _ to say "throw this away":
for (_, value) in someDictionary {}

Another way to solve this is to use reduce. I wouldn't say this is necessarily simpler though:
total = anythingAndEverything.reduce(0.0) { (x, y) -> Double in
    if let value = y.value as? Bool {
        if value {
            return x + 2
        } else {
            return x - 3
        }
    } else if let value = y.value as? Double {
        return x + value
    } else if let value = y.value as? Int {
        return x + Double(value)
    } else if let value = y.value as? String {
        return x + 1
    } else {
        return x
    }
}


Q:

Difference in behaviour between javascript click() and user click on a button using JSF

I have a form which, when the button gets clicked by a user, redirects to another page, but when I simulate the click with javascript, the redirect fails. Tha ajax calls are exactly the same (except for the javax.faces.ViewState, but have different results.
The form looks something like:
<h:form id="form" onkeypress="trapEnter(event);">
    <h:outputText value="Number" />
    <h:inputText value="#{form.number}" />

    <a4j:commandButton id="act" value="Go" action="#{form.go}" />
</h:form>

The javascript function:
function trapEnter(evt) {
  // cut out to save space

  if (keycode == 13) {
    document.getElementById('form:act').click()
    return false;
  } else {
    return true;
  }
}

When I enter 3 into the text input box and click Go, the page is redirected as expected to the target returned by #{form.go}.
When I enter 3 into the text input box and press enter, #{form.go} is called correctly but the page is NOT redirected.
In both cases form.go is called correctly and returns the correct value for the redirection. Could anyone tell me why the javascript click() does not work, and if I'm doing something completely wrong, please tell me how to do it right.
I'm using Firefox 3.5 if that makes a difference.
Thanks.

A:

I never did find out why this didn't work. As far as I know, it still doesn't work.
However, after asking the same question in the JBoss community forum, there is a different way to achieve this in richfaces:
<rich:hotKey selector="#form" key="return" handler="document.getElementById('form:act').click();"/>

this is included in the page to which it applies. This works.


Q:

Why is my compiler throwing a "Conversion loses (const) qualifiers" error when I call a const getter function?

I am writing a clone of the classic artillery game Scorched Earth (as if there aren't enough of those already), and have run into a problem which confounds me. I have a getter function in my Player class, which returns a const copy of the player's name.
const std::string Player::getName()
{
    return this->m_name;
}

I am using the getter to set the text of a text label on my viewport to reflect the name of the player whose turn it currently is.
void Tanx::handlePlayerEvents(const Player& player)
{
    QObject::connect(&player, &Player::aimChanged, this, [=](int angle) {this->angleSlider->setValue(angle);  });
    this->playerNameDisplay->setText((QString::fromStdString(player.getName())));
}

My compiler is throwing these errors, even though my return value is const, and the QString::fromStdString takes a const reference to an std::string.
1>C:\Users\Dominic\source\repos\Tanx\tanx.cpp(85,74): error C2662: 'const std::string Player::getName(void)': cannot convert 'this' pointer from 'const Player' to 'Player &'
1>C:\Users\Dominic\source\repos\Tanx\tanx.cpp(85,59): message : Conversion loses qualifiers
1>C:\Users\Dominic\source\repos\Tanx\Player.h(63,20): message : see declaration of 'Player::getName' (compiling source file tanx.cpp)

I am having difficulty figuring out what the issue is, and I figure it will probably be embarrassingly clear to somebody with actual coding skill. Thank you for your help!
[EDIT]
Thank you to David Schwartz! Declaring the function, not just the return value as const worked perfectly. Also, a good suggestion to return a const reference to avoid copying.

A:

const std::string Player::getName()

The const here doesn't do anything. You're returning a value -- the value of m_name. A value cannot be const since changing a value always produces a different value.
What you wanted was a const function, one that it is permitted to call on a const-qualified member. You define them as follows:
std::string Player::getName() const

Also, it's pretty common to have a getter like this return a const std::string& to avoid an unnecessary copy. Of course, it does make sense to const-qualify something returned by reference.


Q:

Ajax and javascript not work for all clicks

i have problem when i click on comment button just the first comment button work even thought i have a  for loob where each post has a comment button:
  <textarea id="comment"></textarea>
  <button class="btn btn-success" id="addComment">comment</button>

this the javascript code :
 $('#addComment').on('click', function () {

    postId = event.target.parentNode.childNodes[1].dataset['postid'];
    commentbody=event.target.parentNode.childNodes[2];
    userId=event.target.parentNode.childNodes[2];

    $.ajax({
            method: 'POST',
            url: addComment,
            data: {comment: $('#comment').val(), postId: postId, _token: token,userId:}
        })
        .done(function (msg) {
         $(commentbody).text('');
        alert('done');

        });
});`

i want to know how to let the javascript function work through the loop

A:

you're using id selectors which are unique, apptempt to use class selectors.
https://api.jquery.com/id-selector/
$('#addComment') => will query dom for element with ID addComment
https://api.jquery.com/class-selector/
$('.addComment') => will query dom for elements with class addComment
Example:
  <textarea class="comment"></textarea>
  <button class="btn btn-success addComment">comment</button>

\\js

$('.addComment').on('click', function (event) {
    postId = event.target.parentNode.childNodes[1].dataset['postid'];
    commentbody=event.target.parentNode.childNodes[2];
    userId=event.target.parentNode.childNodes[2];
    var comment: $(event.target).find(".comment").val();

$.ajax({
    method: 'POST',
    url: addComment,
    data: {comment: comment,

....


Q:

Are JavaScript MVC Frameworks only for 'single-page' apps?

I've been looking into several of the JavaScript MVC Frameworks (Backbone.js, Spine, SproutCore,etc.) and it seems to me that all of these are designed to act as 'single-page' applications. All of the examples I see have an index page that act as a front controller, and use # or #! style URLs for different pages, and handle the entire rendering of the page.
I have several projects where I would like to use a more 'traditional' style of URLs, and having more structured JavaScript to handle some of the more complicated parts of the application. are JS MVC frameworks the answer here, or should I be looking for something different?

A:

JavaScript MVC is just a code organization pattern.
They happen to work well with SPA but they can be used in normal applications.
However you don't actually need a JS MVC framework. You can just write modular JavaScript using some kind module loading strategy.
As long as you separate modules into separate objects / functions / units the code should be structured and clean.


Q:

Git checkout to first commit

How do I list all of my git branches after checking out my first commit?
For example
git log --oneline

displays all of my branches:
06c4b5c Version 3 of Hello World
efa167f Version 2 of Hello World
47a33c8 Hello World

If I check out my first commit
git checkout 47a33c8

this message is displayed

You are in 'detached HEAD' state. You can look around, make
  experimental changes and commit them, and you can discard any commits
  you make in this state without impacting any branches by performing
  another checkout...

then if I do this:
git log --oneline

only the first commit is displayed now:

47a33c8 Hello World

My question is, if I did not know the location of HEAD was at 06c4b5c originally, how do I return to this location after checking out the first commit?
Also, I get this error

Error: pathspce '06c4b5c' did not match any file(s) known to git.

when i try to checkout 06c4b5c
git checkout 06c4b5c

A:

You can use git reflog to see where you were before. You'll see an entry like
checkout: moving from master to 47a33c8

Just do git checkout master to return to that branch.
To list all the branches, use git branch -l.


Q:

Testing the Patch odata webapi method

I need to test the following Patch method in my odata controller from my test project.
[ValidateModel]
        [AcceptVerbs("PATCH", "MERGE")]
        public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<User> patch)
        {
            var user = await db.Users.FindAsync(key);
            if (user == null)
            {
                return NotFound();
            }

            patch.Patch(user);

            Validate(user);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                db.Entry(user).Property(p => p.UserType).IsModified = false;
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(key))
                {
                    return NotFound();
                }
                throw;
            }

            return Updated(user);
        }

The code in the test project is as follows. Could someone tell me how do I pass value to the Delta parameter. Currently I am getting compilation errors at line  controller.Patch(1,   user);.
[TestMethod]
        public void TestPatch()
        {
            // Arrange
            var controller = new UsersController();

            var user = new User();
            user.Id = 1;
            user.Lastname = "Johanson";
            // Act
            controller.Patch(1,  <System.Web.OData.Delta> user);

            // Assert
        }

A:

You can also declare the delta using the dynamic keyword and set the properties directly:
dynamic delta = new Delta<User>();
delta.Id = 1;
delta.Lastname = "Johanson";

A:

var delta = new Delta<User>(typeof(User));
delta.TrySetPropertyValue("Id", 1);
delta.TrySetPropertyValue("Lastname", "Johanson");

I don't know if there are any helpers to make that easier

A:

@yenta's answer is perfectly fine, but if you can, also consider using the nameof (since C# 6.0)
var delta = new Delta<User>(typeof(User));
delta.TrySetPropertyValue(nameof(User.Id), 1);
delta.TrySetPropertyValue(nameof(User.Lastname), "Johanson");


Q:

Reduce 2d irregular shapes to regular primatives

I'm looking for an algorithm or tried & tested method for analyzing irregular polgygons and reducing them to primitives (squares, rectangles, trapeziums). A way of recurrsively looking over shapes to determine the best fit for regular polygons.
see image blow

The black shapes are the irregular polygons and the blue depicts the desired regualar, which fits inside. The left example should be straight forward but that's because it's a case of finding the a rectangle that can fit in the largest shape. The polygons will be of an undetermined size (but let's say they have less then 32 sides) What I'm hoping for is to be able to break up polys into several regualar ones - which is where I'm a little lost.
Sadly, I've no code at this point as I'm stuck to know the best way forward. The script will be done in pure JavasScript. This isn't homework :)

A:

First of all, you need to check whether your polygon is convex or concave. If it is the latter, then you need to view it as several convex polygons "put together" and handle them separately. (It is easy to your mind to imagine a large pair of scissors which cuts the polygon into several smaller polygons). When this is done, you either have a single polygon, or several polygons.
For each polygon, calculate the gravity point of the polygon and (P(i), P((i + 1) mod n), G) will form a trivial form, a triangle. These triangles will solve your problem.
If you need shapes with four angles, then four consecutive points form a shape of four angles. But this approach might leave you with a smaller polygon with lesser number of angles in the middle of the main polygon, which will have to be handled.


Q:

Becoming better at Vim

I've been using Vim for quite a long time, but I'm at a level where I use insert mode most of the time, and I still use the arrow keys to move around(!).
I feel like I'm not getting the best out of my lovely editor, particularly regarding navigating (especially code), copy & pasting, and doing other manipulations of existing code. (though I am quite comfortable with complicated search/replace patterns).

How should I go about learning more?
What resources would people recommend?

A:

"Why, oh WHY, do those #?@! nutheads use vi?" is a nice introduction to "the Vim way", especially about text objects which are one of the most defining features of Vim.

A:

Here are some awesome screencasts that should give you an idea of what to learn next. There are also videos for intermediate and advanced topics, but the novice ones are in fact the most important.
Also, when I felt that I was stagnating and not really learning "the Vim way", I chose to disable arrow keys in both normal and insert mode. This forces you to use ESC to get somewhere, and makes you think more Vim-like. Ultimately, I enabled arrow keys again in insert mode, but I hardly ever use them. There is, most often, better ways to get around.
map <up> <nop>
map <down> <nop>
map <left> <nop>
map <right> <nop>

And especially
imap <up> <nop>
imap <down> <nop>
imap <left> <nop>
imap <right> <nop>

A:

type vimtutor on the command line
go into vim, type :help or <F1>
subscribe to mailing list
official vim docs


Q:

Why "recursive sql" is used in "Dictionary-Managed Tablespaces" in oracle?

Oracle documents points out that locally managed tablespace is better than dictionary-managed tablespace in several aspects. one is that recursive sql is used when database allocate free blocks in dictionary-managed tablespace.
Table fet$ has columns (TS#, FILE#, BLOCK#, LENGTH)
Could anyone explain why recursive sql is used for allocation with fet$?

A:

You seem to be interpreting 'recursive' in the normal programming sense; but it can have slightly different meanings:

drawing upon itself, referring back.
The recursive nature of stories which borrow from each other
(mathematics, not comparable) of an expression, each term of which is determined by applying a formula to preceding terms
(computing, not comparable) of a program or function that calls itself
...

If you interpret it as a recursive function (meaning 3) then it doesn't quite make sense; fet$ isn't updated repeatedly and an SQL statement doesn't re-execute itself. Here 'recursive' is used more generally (meaning 1, sort of), in the sense that the SQL you run generates another layer of SQL 'under the hood'. Not the same SQL or the same function called by itself, but 'SQL drawing upon SQL', or 'SQL referring back to SQL', if you like.
The concepts guide - which is where I think you got your question from - says:

Avoids using the data dictionary to manage extents

Recursive operations can occur in dictionary-managed tablespaces if
  consuming or releasing space in an extent results in another operation
  that consumes or releases space in a data dictionary table or undo
  segment.

With a table in a dictionary managed tablespace (DMT), when you insert data Oracle has to run SQL statements against the dictionary tables to identify and allocate blocks. You don't normally notice that, but you can see it in trace files and other performance views. SQL statements will be run against fet$ etc. to manage the space.
The 'recursive' part is that one SQL statement has to execute another (different) SQL statement; and that may in turn have to execute yet another (different again) SQL statement.
With a locally managed tablespace (LMT), block information is held in a bitmap within the tablespace itself. There is no dependence on the dictionary (for this, anyway). That extra layer of SQL is not needed, which saves time - both from the dictionary query itself and from potential concurrency delays, as multiple queries (across the database, for all tablespaces) access the dictionary at the same time. Managing that local block is much simpler and faster.
The concepts guide also says:

Note:   Oracle strongly recommends the use of locally managed tablespaces with Automatic Segment Space Management.

As David says, there's not really any benefit to ever using a dictionary managed tablespaces any more, and unless you've inherited an old database that still uses them - in which case migrating to LMT should be considered - or are just learning for the sake of it, you can pretty much forget about them; anything new should be using LMT really, and references to DMTs are hopefully only of historic significance.

I wanted to demonstrate the difference by running a trace on the same insert statement against an LMT and a DMT, and showing the extra SQL statements from the trace file in the DMT version; but I can't find a DMT on any database I have access too, going back to 9i, which kind of backs up David's point I suppose. Instead I'll point you to yet more documentation:

Sometimes, to execute a SQL statement issued by a user, Oracle
  Database must issue additional statements. Such statements are called
  recursive calls or recursive SQL statements. For example, if you
  insert a row into a table that does not have enough space to hold that
  row, then Oracle Database makes recursive calls to allocate the space
  dynamically. Recursive calls are also generated when data dictionary
  information is not available in the data dictionary cache and must be
  retrieved from disk.

You can use the tracing tools described in that document to compare for yourself, if you have access to a DMT; or you can search for examples.
You can see recursive SQL referred to elsewhere, usually in errors; the error isn't directly in the SQL your are executing, but in extra SQL Oracle issues internally in order to fulfil your request. LMTs just remove one instance where they used to be necessary, and in the process can remove a significant bottleneck.


Q:

GitHub: searching through older versions of files

I know that using GitHub I can search through all the current versions of my files in a repo. However, I would also like to search through the older versions of my repo files. For example, say, I used to have a function called get_info() in my code, but deleted it several versions ago, is it possible to search for get_info and find the code. If it is not possible using GitHub, is it possible from the git command line?
EDIT
Thanks to @Mark Longair for showing how this can be done from the git command line. If it's not possible in GitHub it would be a great feature to have.

A:

Currently, I don't believe it's possible to search within the complete history of a repository's code on the github website - the closest is just searching within the current code of a repository with the "code search" option on this page.
However, from the command line, you can find any commits that introduced or removed lines mentioning get_info with the -S option to git log.  e.g.:
git log -Sget_info -p

(n.b. there should be no space between -S and the search term)
(also note: to search for more than one word, surround in '):
git log -S'get info' -p

So, at a minimum that should find the commit where the function was first introduced and the one that removed it.  I added the -p so you can also see the patches - if lots of commits introduced changes that mentioned the function that may be helpful.  If the function was only on another branch it might also be useful to use --all to search all branches.
Jefromi points out in a comment below that git 1.7.4 will introduce the -G option as an alternative - this change is summarized in a recent blog post from Junio Hamano (git maintainer): http://gitster.livejournal.com/48191.html


Q:

Arguments to attribute constructor style functions

I've seen code like this: (Apple based code)
__attribute__((constructor))
void do_action(int argc, const char **argv, const char **envp, const char **things, struct ProgramVars *)
{
   //
}

Which is odd to be because I read that constructors style functions are supposed to be void. Where are those arguments coming from, can I choose what those parameters can be? Is this an Apple only thing for gcc/clang?
This code is supposed to be used with DYLD_INSERT_LIBRARIES, (Linux's LD_PRELOAD).
Is that a special reason why it gets arguments?

A:

Functions with attribute constructor can have the same arguments as main has. They can't differ. LD_PRELOAD has nothing common with it. This feature is heavily based on glibc library (don't know about others) and is acceptable for all compilers, that use glibc and support constructor attribute. On Linux it works fine.
Look at the piece of code, where your function do_action is called:
for (size_t i = 0; i < size; i++)
  (*__init_array_start [i]) (argc, argv, envp);

It is placed in glibc library within path *csu/elf-init.c
I also deem, that your argument struct ProgramVars * can't be assigned and can be only nullptr.


Q:

How do I get Crucible and Vanguard marks?

Several vendors require Crucible and Vanguard marks for purchasing certain items, but the tooltips say nothing about how to get them. How and when do I get these marks?

A:

Crucible Marks are obtained by anything and everything PvP. The amount you get varies on performance and game mode.
Vanguard Marks you get by doing the Strike playlist (opens at around level 17). You can also gain marks at a much slower rate by doing other PvE interactions, like patrolling and random events that appear during patrols. The amount you get varies on the Strike Difficulty selection you chose.
Both kinds of Marks have a weekly earn limit of 100 before you can gain more again. The time renews on Tuesdays, IIRC.


Q:

WebDriver with Java - click to open a link using xpath

I want to open a a link on a webpage. The link appears to be within a unordered list which resides within in a  tag. The url to the web page is selftechy dot com. The tabs are home, about, selenium.
I attempted to open the link using driver.findElement(By.linkText("Selenium")); but page seems like lost its styling. I also tried with xpath method, but it doesn't work either. Please explain to me why it doesn't work and how should I modify the code to make it work properly. Thanks for your help.
HTML code fragment:

Home

About

Selenium

webdriver code to open the link
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.*;

import org.junit.Before;
import org.junit.After;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class selftechyTestng
{
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception
    {
        driver = new FirefoxDriver();
        baseUrl = "http://selftechy.com/";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }
    @Test
    public void searchElements() throws Exception{
        driver.get(baseUrl);

            //use By.linkText method the page lost its styling
            driver.findElement(By.linkText("Selenium"));

        //use xpath method to open the link doesn't work either
        List<WebElement> elements = driver.findElements(By.xpath("//div[@id=page]/*[3]")).click();
        driver.findElement(By.xpath("//div[@id=page]/*[3]")).click();
    }

}

A:

Why do you search for the div and then the child element - Is there any particular reason? I don't see any advantage and certainly you are then not getting the a element which you actually want to click. In my opinion it is much simpler to use
driver.findElement(By.xpath("//a[@title = 'Selenium']")).click();

Using your approach you have to use
driver.findElement(By.xpath("//div[@id = 'page']/ul/li[3]/a")).click();


Q:

How to press a login button of a website programmatically

I am loading a website into a WebBrowser in a winform. I wish to login using a log and pass automatically via vb.net
I have the following code executing once the page loads
 WebBrowser1.Document.GetElementById("e").SetAttribute("value", "email@address")
                WebBrowser1.Document.GetElementById("p").SetAttribute("value", "password")
                WebBrowser1.Document.Forms(0).InvokeMember("submit")

I am able to fill in the boxes that need to contain the Log and pass but I am not able to fire off the login button of the webpage automatically. After research I am confident that I replicated the sample I found properly but obviously there is an issue. The 'button' isn't pressed because I don't get anything happening. When I press the website login manually it logs in correctly using the data that I filled in .
the webpage link is https://www.weatherzone.com.au/customise.jsp
and the relevant source data is below
 <form action="/customise.jsp" method="post" style="width: 75%; text-align: left;">

    Enter your email address:
    <input style="width: 95%;" type="text" name="e" id="e" />

    Enter your password:
    <input style="width: 95%;" type="password" name="p" id="p" />

    <input type="checkbox" name="rmbr" id="rmbr" value="1" />
    Remember me (check this box if you are a regular user of this computer)

    <input class="submit btn" type="submit" name="target" value="login" />

  <input type="hidden" name="dest" value="/" />
</form>

A:

I applied this logic:

Put the code in a DocumentCompleted event to run the code after the document completed.
The DocumentCompleted also raises when an iframe document completed, so to get rid of iframes use a criteria like comparing e.Url with the base url know.
Find the submit button by name and click on it.

And it worked properly. It redirected to the same url and showed a red not authenticated message.
Code:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    If (e.Url.ToString().StartsWith("https://www.weatherzone.com.au")) Then
        WebBrowser1.Document.GetElementById("e").SetAttribute("value", "email@address.com")
        WebBrowser1.Document.GetElementById("p").SetAttribute("value", "password")
        WebBrowser1.Document.All().GetElementsByName("target").Cast(Of HtmlElement).First().InvokeMember("click")
    End If
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.WebBrowser1.Navigate("https://www.weatherzone.com.au/customise.jsp")
End Sub

To make the code more stable, add required null checkings.


Q:

which class in a gui program is prefered to handle events?

I have got confused by these lines of code:
public class AL extends Frame implements WindowListener,ActionListener {
Button b;
b = new Button("Click me");
b.addActionListener(this);
...

what I understand is that the frame is set as event handler to "its" button.
Is it acceptable to set event handlers that are themselves part of the gui while separate from the source of event?(I mean maybe a button class should handle its events.)
As I have seen many of the events in codes are handled by the jframe. Is there any special purpose behind it?
previously thanks for your time!

A:

The reason you see such code (I've seen a lot of it too, I admit), is that some programmers, especially those writing AWT and/or Swing code, tend to put tons of GUI logic into a single class. The reasons for this vary, but several common ones are:

They've seen such code in examples while learning
They're reluctant to use anonymous classes, or perhaps there's so much code in the event listener's methods that an anonymous class doesn't seem applicable
They believe it's "easier" to understand the code, if the event handling of all child components is done directly in the parent container's methods
They're afraid to have "too many classes" in the project (I'd like to find whoever started that misconception !)

From my experience, a lot of GUI code looks like that. Is that a good way of programming ? ABSOLUTELY NOT !
Any methodology book you read will tell you the same. Such classes are breaking every possible principle of good design. The most basic example would be SRP (http://en.wikipedia.org/wiki/Single_responsibility_principle).
Moreover, GUI classes that handle events as methods of the class, tend to blow out of proportion, and unfortunately, classes of several thousands of lines of code is something I've seen many times in different projects and companies.
Don't fall into this trap. Keep your classes short, have a different class for each of the inner components, unless it's a regular component with a very simple initialization (in which case it would still be preferable to have a factory class do the initialization).
Keep event handling in anonymous classes when there's very few lines of code in the handler, and in separate classes when there's more than a line or two of code.
In short, GUI code is no different than other OO code, and should adhere to the same principles and methodologies.


Q:

Open API for nutritional information and/or food barcodes?

I've seen many applications (mobile and web) that use a database of nutritional information and barcodes to track daily food consumption. Smartphones have the ability to scan barcodes, and many mobile applications have started to include a barcode scanner to search for and log food consumption. Calorie Counter by MyFitnessPal is an example of this.
I would like to know where/how they get their resources. I found the National Nutrient Database provided by the USDA, but the most structured format that comes in is PDF. It also doesn't provide the barcodes that would be required for an app like Calorie Counter. It seems like the most reasonable approach for these applications would be to call an open API, rather than scraping PDFs.
Is there an open API for nutritional information and/or food label barcodes?

A:

The complete USDA National Nutrient Database for Standard Reference can be downloaded as ASCII text files from https://www.ars.usda.gov/Services/docs.htm?docid=8964 — no PDF scraping necessary :)
Regarding product barcodes, have a look at Open Product Data, a new project by the Open Knowledge Foundation.

A:

Have a look at OpenFoodFacts, which is a "free, open and collaborative database of food products from the entire world."  It contains almost 920,000 items from around the world and may be helpful in solving your issue.

A:

The USDA now provides an Open API for the National Nutrient Database for Standard Reference using data.gov. You need a data.gov API key in order to access this, and requests are sent to api.data.gov using the REST protocol.


Q:

Halt PHP CLI script to give the user possibility to exit with CTRL-C

How to pause the execution of a command line script to give the user the possibility to exit it with a Ctrl+C?
For example I have this script for deleting a user id from a number of tables, but would like to halt the script before really doing it:
<?php

define('DBHOST', '/tmp');
define('DBNAME', 'XXX');
define('DBUSER', 'YYY');
define('DBPASS', 'ZZZ');

$TABLES = array('pref_game',
                'pref_hand',
                'pref_luck',
                'pref_match',
                'pref_misere',
                'pref_money',
                'pref_pass',
                'pref_rep',
                'pref_status',
                'pref_users'
        );

if ($argc != 2)
        exit("Missing user id\n");

if (!preg_match('/^([A-Z]{2}[0-9]+)$/', $argv[1], $matches))
        exit("Invalid user id\n");

$id = $matches[1];
printf("Deleting user %s Press CTRL-C to abort\n\n", $id);

# XXX stop here, but how? XXX

try {
        $db = new PDO('pgsql:host=' . DBHOST . '; dbname=' . DBNAME, DBUSER, DBPASS);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        foreach ($TABLES as $table) {
                $sql = sprintf('delete from %s where id=?', $table);
                run_sql($db, $sql, $id);
        }

} catch (Exception $e) {
       exit('Database problem: ' . $e->getMessage());
}

function run_sql($db, $sql, $arg) {
        $sth = $db->prepare($sql);
        $sth->execute(array($arg));
        printf("SQL: %s\nAffected rows: %d\n\n", $sql, $sth->rowCount());
}

?>

Using CentOS Linux 5.5 + PHP 5.1.6 + PostgreSQL 8.4.7.

A:

Try with:
    printf("Deleting user %s Press CTRL-C to abort, enter to continue\n\n", $id);
    $fp = fopen("php://stdin","r");
    fgets($fp);

    echo "OK!";


Q:

What medal did the referee in the FIFA world cup get?

The referee, Nicola Rizzoli, seemed to have received a medal in yesterday's finale. What kind of medal is this?

A:

It would a momento or souvenir, rather than a medal. This is common in all sports, to give the officials souvenirs of a significant moment in their officiating careers.