Regular expressions help

Question: I am trying to write a regular expression in php that checks to make sure the string passed in is one of three things, however I am having a hard time (I really struggle with regex).
I need to make sure that my received parameter contains one of these three things, and nothing else:

"|" and that's it just a single pipe  OR
"" and that's it just an empty string OR
"|1|534|3453|23|213|2|"  A long string that uses pipes as a delimiter for a series of numbers

Thank you for your help (this is continually a problem for me, think I need to buy a book exclusively on regex)
Comment: Might I suggest [Mastering Regular Expressions](http://oreilly.com/catalog/9780596528126) (AKA the Owl Book)
Comment: There are two things that will help you read regular expressions. This tutorial: http://www.regular-expressions.info/tutorial.html and this actionscript site to try out your regex: http://gskinner.com/RegExr/
Answer: preg_match('/^(?:\|(?:\d+\|)*)?$/', $input);

Comment: Character for character, exactly the same as my answer. Too slow.
Comment: @sdleihssirhc What are the odds of that?
Comment: We should both buy lottery tickets.
Comment: It'd be more maintainable if it were split into 3 checks, but this'll do it.
Comment: @Jeff Three checks? What do you mean?
Comment: +1. Of course, this assumes that the string (if it's not empty) must start and end with `|` (that is, `123|`, `456|` and `78|90` are not valid).  I believe that's correct, but the question wasn't very clear on that point, so it's a good idea to make the assumption explicit.
Answer: The easiest way to do this would be to split it into three separate checks:

The string is just a single pipe (strcmp($str,"|") == 0)
The string is empty (strlen($str) == 0).
The string matches the regex /^[0-9\|]+$/

Don't make it harder than it needs to be by trying to cram all of those checks into one regular expression. Your code will be more easily understood, and future maintainers of your code will thank you.
Edit: Just to display what I'm talking about, here's some sample code:
if( strcmp($str,"|") == 0 ||
    strlen($str) == 0     ||
    preg_match('^[0-9\|]+$', $str) {
  ...
}

vs
if( preg_match('/^(?:\|(?:\d+\|)*)?$/', $str ) {
  ...
}

At a glance, which one executes the ... if $str is empty?
Comment: That's true, you really only need the regex to test the 3rd condition he listed.  Just goes to prove the old joke: A programmer has a problem.  "I know," he says, "I'll use a regular expression!" Now he has two problems.
Comment: I agree.  Separate it into 3 Regex, and it will be much more maintainable than either of the other current answers.
Comment: You don't even need three regular expressions. The first two checks are trivial uses of `strlen()` and `strcmp()`. I've edited my answer to display these checks.
Answer: (^(\|)([0-9\|]{0,})(\|)$)|(^(\|)$)|()
use above regex and if no mathches your string is not valid, othervise its valid, and try to check of empty if str_len($string) > 0 then check regex

Regular expressions help


New home with gaps in stairs

Question: The stairs in our home being built (production builder) is concerning. The gaps in risers and treads doesn't seem right. When seeing all other homes in same neighborhood under construction they do not have gaps and risers are plywood allowing a butt to be flush. There is carpet going to be installed so the builder is not concerned about gaps. I know it will be covered but years later what problem will this cause when we want hard finished stairs. My other concern is there was no wood glue used at all. Will I be dealing with squeaky stairs in a year? What things can I do myself to ensure no squeaks? Drywall has already been installed so I have no access to underside.
Comment: This is the way our stairs were built, 41 years ago.  Other places in the house squeak quite a bit, but not the stairs.
Answer: Those look like temporary steps to me. For carpeting you usually see 1-1/8" bullnose particle board treads and 1x8 or 3/4" plywood risers.
Rarely is two-by lumber left as a final product, as it's heavier-duty than necessary and creates very thick and squarish nosings when carpeted. We'd commonly do something like that, or doubled scrap plywood, until after taping and painting is done, then install the final materials using construction adhesive.
Yes, it should be done better, but that's my opinion. It really comes down to your relationship with the builder and your contract. Ask your builder if that's the final state.
Comment: OP said: "There is carpet going to be installed so the builder is not concerned about gaps" so it sounds like this is the final state.
Comment: Why would you put risers on temporary stairs? Seems like a waste to me (but what do I know).
Comment: We don't know the origin or context of that statement. Therefore, I don't take it as evidence that the question has been asked and answered.
Comment: @stannius Because you don't want workers breaking their legs because they slipped through the stairs carrying half their weight in materials...
Comment: It's kind of a standard approach to put temporary steps in during construction, right?  That way you don't have to worry much about protecting them from damage.  These steps look like hell from the pictures to that point.  Even if the plan is to cover them, doesn't the carpet need to be tacked in right where that gap is?
Comment: I had the same thought, but they're required for safety on finished deck stairs, and may be required in some jurisdictions for jobsite safety as well.
Answer: I would also say those look like temporary stairs, but lets ignore that for the moment. You correctly observe that there are gaps on every stair between the tread and riser and the photos show that the gaps are even. Now having well made stairs is very important in that uneven or other badly made stairs are a safety risk. gaps are often a pointer to uneven stairs, but all the gaps are even, which points either to careful deliberate workmanship or jigs both of which are good things. Overall these stairs show an interesting mix of over build and cost cutting that leads me to believe that they were built by an experienced carpenter with cheapest materials intending them to be a temporary stair. depending on humidity and other factors they look like they may last several years before warping gets annoying or dangerous, but they do not have shims under the treads and behind the risers that would allow a stair to last decades. Final analysis: well made but temporary, replace before carpeting. The gap is not a problem, the lack of shims or wedges is.
Answer: No, those gaps are nothing to worry about. As you correctly stated, when the stairs are carpeted, they will be invisible and their location makes them unimportant.
If you do, in fact, want exposed wood stairs at some future date, the wood you see there is not the wood you would want to be exposed. You would either replace the treads and apply a "veneer" over the risers, or replace both risers and treads.
If you replace both, problem solved. If you replace only the treads, the problem can still be solved by using a sturdy "veneer" layer on the risers. Contrary to what you may think, it is actually quite difficult to kick that exact spot, so "sturdy" is a relative term. You obviously don't want true veneer, which is often 1/32" or thinner, these days, but you don't need 3/4" plywood, either. 1/8" veneered plywood would do fine.
As for squeaks, this construction method actually reduces one source of potential squeaks, which is the movement of the tread against the riser. You still may eventually get some squeaking due to other sources of friction, but there's not much you can do to totally eliminate that possibility. Wood moves. Even Giant Redwoods sway in the wind. As long as it's quality construction, using screws, it's a low probability.

New home with gaps in stairs


how can i insert login control on the top of default page

Question: in my master page there is a login status when i click on it the page is redirected to login page.now i want to create  login control in the home page itself so that users dont have to visit loginpage again and again..i guess i cant create the login control in the masterpage .it has to be in the default page but then how can i put that control on the top of the page . i have also used login control in masterpage but then my other control ion login page doesnt work properly
Answer: You can add a Login control to your master page by adding something like this to the markup
<asp:Login runat="server" ID="MyLoginControl" />

Or my dragging the Login control onto the master page's designer from the Toolbox.
To hide the login control when the user is logged in, add this code to the master page code-behind:
if (Page.User.Identity.IsAuthenticated)
{
   MyLoginControl.Visible = false;
}

Comment: let me tell my exact problem.i want
1) login control on home page
2) the moment user logins it should become invisible in other pages as that is not the case right now.
3) my second login control in login.aspx should also work properly
Comment: Added code example for hiding control when user is logged in.
Answer: Ok, let me make the following assumptions.
Currently you have:
- one masterpage
- one default page (of course)
- one login page
- bunch of other pages
You want to have:
- one masterpage (with login control)
- one default page (with a main login control)
- no login page
- bunch of other pages
My suggestion:
Option 1
- one masterpage (with login control at the top of page)
- one default page (with a main login control NOT using the materpage)
Option 2
- one masterpage (with login control at the top of page that can be hidden)
- one default page (with a main login control and hiding the masterpage's logincontrol)
Option 3
- one masterpage A (without login control)
- one masterpage B using masterpage A (with login control at the top of page)
- one default page (with a main login control using masterpage B)
- bunch of other pages (using masterpage A)
Comment: i think the last option will resolve my purpose,,ok let me try this.thnx for ur reply,i l let u know if i can solve it,,jst give me one hour
Comment: ohh wait if i use another masterpage B using A then is it possible to insert the login control on the top of the page of mastrpage B
Comment: @sumit: yes, masterB = masterA + login-control
Comment: but what i have noticed that the login control cant come on the top,,i m a little bit confused when B = A + login control B acts as a simple page inheriting A
Comment: can u send me some posts regarding my problem.
Comment: @sumit: I think I wasn't clear enough. I eman MasterB using MasterA as it's masterpage. Not inheritance. :)
Answer: You can add a Login control to your master page by adding something like this to the markup
<asp:Login runat="server" ID="MyLoginControl" />


Javascript Templates - Deep nesting is it possible

Question: I am constructing a task app ( For fun) & i just sat down thinking about this problem. I will put the question on my mind in words here.
Model is extremely simple, it contains collection of Project. Each Project contains a TaskList these TaskList is nestable i.e for example a Task Design FrontPage can have Design Header as another TaskList. Each TaskList contain Tasks. How will a typical javascript template look like for this problem. I could not come with one that works this scenario. This problem is as same as N level nested Menu, how would you render it using templating library.

    {{#Projects}}

        {{ProjectName}}

        {{#TaskList}}

{{TaskListName}} {{CreatedBy}} The Problem Comes here - How do i Render a #TaskList
            here

        {{/TaskList}}

    {{/Projects}}

btw if anyone has asp.net solution (Ideas for this let me hear them), N level deep nesting is the thing i am unable to overcome right now.
Answer: You could define your TaskList as a partial and include it recursively as the documentation hints.
Templates:

JavaScript:
    var data = {
    Projects: [
        {
        ProjectName: "Project 1",
        TaskList: [{
            TaskListName: "Name 1",
            CreatedBy: "Person 1"},
        {
            TaskListName: "Name 2",
            CreatedBy: "Person 2",
            TaskList: [{
                TaskListName: "Sub Name",
                CreatedBy: "Same Person"},
            {
                TaskListName: "Sub Name 2",
                CreatedBy: "Person 1"},
            {
                TaskListName: "Sub Name 3",
                CreatedBy: "Person 3-2",
                TaskList: [{
                    TaskListName: "Sub Sub Name",
                    CreatedBy: "Person 3-3"}]}]}]},
    {
        ProjectName: "Project 2",
        TaskList: [{
            TaskListName: "Name 3",
            CreatedBy: "Person 3"},
        {
            TaskListName: "Name 4",
            CreatedBy: "Person 4"}]}]
},
    template = $('#projects').html(),
    partials = {
        taskList: $('#task-list').html()
    },
    html = Mustache.render(template, data, partials);

document.write(html);

Here's the jsFiddle to see it in action- http://jsfiddle.net/maxbeatty/ND7xv/
Comment: and me thinking that partials were of less use. Awesome :) thank you for teaching me never to look-down on something
Comment: was looking for this from very long time..would have given double vote up...if i could...!!


Perl cannot find and open existing file file name even I can print out exactly the same file name

Question: I'm having the following problem like this:
I tried to traverse through all the sub-directory folders with numeric name, e.g.: 0/ 1/ 2/ ...
and try to check files named like this: combine_0_arc combine_1_arc ... in which the number in between is the same as the sub-folder name which this file exists, and here's how I do it:
#!/usr/bin/perl -w
use strict;

opendir(DIR, "./") or die "Failed to open directory: $!\n";
my @DirName = readdir(DIR) or die "Unable to read current directory: $!\n";
#closedir(DIR);

foreach (@DirName){
    chomp;
    my $CurrentDir =$_;
    next if ($CurrentDir eq ".");
    next if ($CurrentDir eq "..");
    if($CurrentDir =~ /^\d+$/){
    #    print "Iteration directory: $CurrentDir\n";
        opendir(SUBDIR, $CurrentDir) or die "Unable to read current directory: $CurrentDir\n";
        my @SubDirFiles =  readdir(SUBDIR);
        foreach (@SubDirFiles){
            chomp;
  #          if($_ =~ /combine_0_arc/){next;}
            if($_ =~ /combine_\d+_arc$/){
                my $UntestedArc = $_;
           #     print "Current directory: $CurrentDir\n";
           #     print `pwd`."\n";
           #     print "Combine_arc_name:$UntestedArc\n";
                open (FH, "<", $UntestedArc) or die "Cannot open file $UntestedArc:$!\n";
            }
          }
        }

It seems I'm getting the following error message:
Cannot open file combine_0_arc:No such file or directory
and I tried to print out the folder name and the file name for each iteration it seems it's printing out correctly. I tried to chomp those trailing spaces or carriage returns for each file name or folder name but it seems it's not working. Can anybody explain me what's happening there? Thanks a lot!
Comment: Please ignore the last missing enclosing bracket at the end. Looks like I'm missing with one when I copied my code here. And the level of directory I'm invoking my script is the root directory where it holds all sub-directories: 0/ 1/ 2/ ...
Answer: The readir returns bare  file name, without the path.  So add it
foreach my $CurrentDir (@DirName) {
    # ...
    opendir my $SUBDIR, $CurrentDir;
    my @SubDirFiles = map { "$CurrentDir/$_" } readdir($SUBDIR);

    foreach my $untestedArc (@SubDirFiles)
    {
        if ($UntestedArc =~ /combine_${CurrentDir}_arc$/) {
             # ...
        }
    }
}

where the regex uses that directory's name, not any number.
Notes

readdir doesn't add a newline, no need to chomp (it doesn't hurt though)
use lexical filehandles
declare the loop variable (topicalizer) in the foreach statement

This answer assumes that your current working directory is the one with @DirName subdirectories.
Comment: Thanks a lot. Your solution works out fine. I tried to call system command to change to current directory before but it failed. You guys are of great help. Thanks
Comment: Welcome. Changing the directory is indeed yet another way. Inside the loop over `@DirName` you say `my $old = cwd; chdir $CurrentDir;`. (Need `use Cwd;` for `cwd`.) Then `readdir`'s output (filenames without path) are the filenames in your current working directory, so then you don't prepend the directory name. But, you'll have to change the directory back at the end of the loop, `chdir $old;` All this assumes that your current working directory is the one with `@DirName` subdirectories
Comment: @王云龙 I corrected my previous comment, a piece of code was wrong. (`chdir` does _not_ return the current working directory before changing it.)  Just letting you know in case you intend to use it.
Answer: readdir just returns the file names in the directory, i.e. the name relative to the directory given to the matching opendir. But, what you need for open is either the absolute name of the file or the name relative to the directory you are currently in (current working directory). Since opendir does not magically change the working directory (this could be done with chdir) the working directory is not the same as the directory scanned with opendir and thus the relative file you use within open can not be found within the current working directory.
Comment: Thanks buddy, I forgot there was "chdir" function. I tried `cd $DestinationFolder` before but looks like that way is not working.  This solved my doubts. Thanks a lot


CoreData: migration from 2 models

Question: I have general app model, after was released any body can do plug-in for it, this plug-in can determine new db parts which merged with my general db. After some time i 'll release new db version^ and plug-in writers may release new version of their dbs. So i need map old version of merged db into new version. How i can do this?
Answer: You need to review the migration documentation in Core Data.  Core Data has migration built into it and you can either do light-weight automatic migration or you can create a mapping model for more complex situations.
http://developer.apple.com/mac/library/documentation/cocoa/conceptual/CoreDataVersioning/Introduction/Introduction.html

CoreData: migration from 2 models


Understanding a C program

Question: Hi I have the following program, I understand how pipes work and fork() etc.. but I have a question. why this program doesn't print "baz\n"
the result is :
bar
foo
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    int fd[2];
    char buf[32];

    pipe(fd);
    if(fork()==0){
        dup2(fd[1],1);
        printf("foo");
    }
    else{
        read(fd[0],buf,31);
        execl("/bin/echo","/bin/echo","bar",buf,0);
        printf("baz\n");

    }

}

Comment: `man execl` will help you understand.
Answer: Execl doesn't return back to the original program. It replaces the current process with a new process (the old one wouldn't keep running). It will execute execl("/bin/echo","/bin/echo","bar",buf,0); and never come back to execute the printf. This is why you only get "bar foo" as a result.
If you look at the man pages:
http://linux.die.net/man/3/execl
Look at the first paragraph under description.
Comment: Like @Gangai said you can just swap the two around.
Answer: Your program doesn't write "baz" because it runs at first your execl function, which close the created process of your fork. In other words, you have to put your printf before the exec function :
else{
    read(fd[0],buf,31);
    printf("baz\n");
    execl("/bin/echo","/bin/echo","bar",buf,0);
}

Good luck ! :)
Comment: thank you Actually i don't want to write baz i just want to understand why, now i Do. Thank you for your answers
Comment: @spleeftroner If Gangai Johann's answer solved your question, you should mark it as correct.
Comment: I did it's just because i's been less than 9 minutes so I couldn't choose it as a correct answer ;)

Understanding a C program


.Net MVC 5.2.3: how to create a disabled option out of SelectListItem?

Question: I am trying to create a dropdown  list with a few options disabled so that they are not selectable. Here is my code:
var places = new SelectList(new List<SelectListItem>
{
    new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    new SelectListItem { Selected = false, Text = "Canada", Value = "Canada", Disabled= true},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    new SelectListItem { Selected = false, Text = "Other", Value = "Other"},
}, "Value", "Text");

However, generated HTML for the disabled SelectListItem is merely:
<option value=""></option>

How can I generate the following HTML
<option disabled="disabled"></option>

from SelectListItem?
Thanks!
Answer: The Disabled property will only be respected if you use IEnumerable<SelectListItem>, not SelectList (in the SelectList contructor, you are only setting the properties of Value and Text) and in any case there is little point creating IEnumerable<SelectListItem> then creating SelectList from it when the helper only accepts IEnumerable<SelectListItem>
var places = new List<SelectListItem>
{
    new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    ....
};

then in the helper
@Html.DropDownList(m => m.YourProperty, model.places) // or (IEnumerable<SelectListItem>)ViewBag.places

Side note: SelectList does have an overloaded constructor that takes IEnumerable disabledValues as a parameter (refer documentation)
Comment: Stephen, I used "var places = new List" as you suggested. Then I used DropDownListFor as in: @Html.DropDownListFor(model => model.Place, places, new { @class = "form-control" }). I got compilation error with DropDownList.
Comment: The second parameter does not look right - it would need to be `Model.places` (if places is a property of your model) or `(IEnumerable)ViewBag.places` if your assigning the select list to a `ViewBag` property
Answer: You are not taking into account Disabled property of SelectListItem, so -
Return your model as typeof
IEnumerable<SelectListItem>

instead of
SelectList

And just bind as -
@Html.DropDownList(m => m.Prop, model.places);

Hope this helps.


JavaScript id output only displays for a second then dissapears

Question: I am making a simple JavaScript function where you enter two numbers in a form and then the function determines if the sum of the two numbers is a prime. It all works but when the function displays a message with the document.getElementById("demo").innerHTML and  it is only on the web page for one second then disappears. I want to make it so the message stays until you click on the button again. I have searched this site and other site but have not been able to find anything.
Here is the code:
<!DOCTYPE html>

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

PRIME NUMBERS

Please enter two numbers to be added and see if the result is a prime.

<form name="frm1" >
<input type="text" name="x">
+ <input type="text" name="y">
<button onclick="prime()">click me</button>
</form>

Comment: Your form is submitting - either prevent default for the action on the button (or prevent default on submit for the form) or use an alert to prevent it from continuing on to submit the form.
Answer: The problem is that your "click me" button is actually submitting the form, causing the page to reload (since your <form> doesn't have an action attribute, it submits to the same page). The <button> tag defaults to type="submit". To make it NOT a submit button, you need to change it like this:
<button onclick="prime()" type="button">click me</button>
Answer: I just tried the code, and what happens is simple: your form is posted when you click the button.
In the button onClick, write onClick=" return prime();" and add a
return false;

in your javascript function.
Answer: In your form tag, just add onsubmit="return false;" like this-
<form name="frm1" onsubmit="return false;" >

This will prevent your form from being submitted.


where can I delete the password cache in krusader in xubuntu?

Question: I have installed krusader under Xubuntu and there I stored an ssh-password in the cache.
Now the password changed, and I have no option to re-enter the password.
krusader only tells me, that the authentification failed.
Where do I find the kde security center in Xubuntu?
Answer: First of all, I don't know if Krusader uses a different password store in XFCE or any non-KDE environment, but in KDE it saves passwords in the KDE Wallet. Anyway, you could try to see if you find your password there.
You can start the Waller Manager by running kwalletmanager at a terminal or using Alt+F2. A window should open that will show your wallet; click it to open it in a new window.
In the wallet window, search for your ssh connection (or something like that) in the top text box, or expand Passwords -> Maps in the left tree. If you find your entry, just right-click it and choose Delete.
If the Waller Manager shows more than one wallet, you can find in the KDE System Settings which one is the default. Run systemsettings and go to "Account Details" -> "KDE Wallet"; the default wallet should be selected in a combo box labeled "Select wallet to use as default".
Of course, if there is no kwalletmanager in your system or you can't find your password in there, then Krusader must be storing them elsewhere.
Comment: I had to install it with `sudo apt-get install kwalletmanager` then it was there in systemsettings


TrueType core fonts for the web EULA

Question:
Why is it happening? How can I get rid of this?
Answer: Use the tab key to select "OK"  and then enter

TrueType core fonts for the web EULA


X Server crashes when I try to change settings in Eclipse on remote Linux node

Question: I've written a C++ application in windows, and want to be able to run it on a Linux cluster node without using Wine. I therefore tried to connect to a cluster node (with an X Server running) and once connected tried to compile the code in Eclipse (C++). However, when I try to set up the linking in the Eclipse menu, the program crashes and I get a 'BadWindow (invalid Window parameter)' X Server error.
I found this bug report
https://bugs.eclipse.org/bugs/show_bug.cgi?id=333227
And tried to use -XX:-UseCompressedOops but it made no difference.
What else could it be?
Answer: Well, I found an easy solution; I switched to Cygwin/X instead of the X server software I used before. Not a crash in sight.


Is there a way to filter mail based on timestamp rather than just date in Thunderbird

Question: In thunderbird, we can filter mail based on a number of constraints including date. But, I don't see a way to use timestamp to filter rather than date alone.
Is there no way for it? Sounds strange imo.
Answer: Well, you can filter incoming mail on a timestamp, in a roundabout way.

Go to "Edit / Find... / Search messages..." or press Ctrl + Shift + F.

Click on the Subject dropdown field and click "Customise...".

In the New Message Header field, type Date (or Delivery-date, or
Received, all of these may work)

Click Add.

In the input field, type an exact date string like 05 Feb 2017 21:09. Leave the middle field at Contains.

Click Search.

Your search will turn up all messages that were received at that time. You can't, unfortunately, search for messages received before or after a certain timestamp. For this, you need to widen the criteria, then sort on "Date received".
Comment: Before I saw your answer, I ended up sorting filtered mails by date, selecting mail there within the timestamp range, and then applying the operation I wanted to do. This idea is better I guess.


Ceiling fan blades "click" and experience resistance 4x per revolution

Question: My Hunter ceiling fan worked ok a few days ago. Today, when I turned it on the blades begin to spin only a few cm until they hit a point of high resistance and get "stuck".
So I turned off the fan and tried spinning the blades manually by hand. They spin ok for the first few cm but experience gradual increase in resistance to spinning as they approach 1/4 rotation. At 1/4 of a rotation, the resistance is so great that the blades stop and even begin to rotate the other way for a few cm as if being driven by a release in tension.
However, I can manually push the blade a bit harder (not very hard but more than a light push) and it will overcome the resistance at the 1/4 rotation mark with a "clicking" sound paired with a slight shaking of the motor housing. After surpassing this point of resistance with a click, the process (i.e., increasing resistance as it spins) repeats until it reaches the next 1/4 turn (at which point it either stops and rebounds backwards or clicks as before depending on speed of the manual push).
My question: what's going on here?
Doesn't seem like it's a bearing issue because I read that a bad bearing would prevent any spinning.
Any ideas?
Comment: @Jack but even when I turn it manually it's getting stuck. I think this is a physical obstruction of some kind...
Comment: could be a bug crawled in there somewhere. clean and lube any moving part, and remember that all moving parts will eventually fail.
Comment: UPDATE: turned out to be a wire that had popped loose of a dry-rotted zip tie.
Answer: UPDATE: turned out to be a wire that had popped loose of a dry-rotted zip tie that had been installed with the fan during manufacturing. I guess the fan was old enough for this to happen. The wire apparently gradually eased upward and into the line of rotating components inside the motor casing, thus getting caught.


How can I change a variable after a set amount of time once a view is displayed with SwiftUI?

Question: I have three states of a game: start, playing, end. I want to display a view when the game is in "start" mode and after a few seconds change the game state to "playing" and as a result change the view displayed.
This is what I have so far:
var body: some View {
    ZStack{
        Color(red: 0.96, green: 0.96, blue: 0.96).edgesIgnoringSafeArea(.all)
        if(skateGame.getState() == .start){
            Text("Start is active").onAppear(perform: {
                skateGame.startGame()
             })

        }else if(skateGame.getState() == .end){
            Text("done")
        }
    }
}

Here is some code for the skateGame class:
enum StateOfGame{
    case start
    case player1Set
    case player2Set
    case player1Try
    case player2Try
    case end
}

class SkateGamePlayLocal{

    private let player1 : Player
    private let player2 : Player
    private var stateOfGame : StateOfGame = .start

    init(player1: Player, player2: Player){
        self.player1 = player1
        self.player2 = player2
    }

    func startGame(){
        self.stateOfGame = .end
    }

    func getState() -> StateOfGame{
        return self.stateOfGame
    }
}

How would I go about making this work?
Comment: It's not a "video game" it's just an interface to help play a game irl. It functions just like a normal app showing different views depending on what is pressed or if some time has passed.
Comment: What is the problem? What does not work?
Comment: It never calls "skateGame.startGame()", I'm open to any solution to this, it docent have to be a change of my code.
Comment: I have also tried sleep(3) but that docent display any view until after 3 seconds.
Comment: Can you show some more code?
Answer: The problem is the example code is missing both timer any View "state" that the timer might update to trigger updating the UI, both of which would be essential to make it work.
For a simple example of this that does something similar to what is being asked about have a look at HwS's "How to use a timer with SwiftUI".
Moving the timer out of the view and into SkateGamePlayLocal or something similar will require understanding the role of ObservableObject, @Published, @ObservedObject and @StateObject. Again worth having a look at HwS's resourses on this, e.g. "Sharing SwiftUI state with @ObservedObject"
Good luck.


Updating Like Button After Click

Question: I'm working on a Like button. It's working fine. After Like button completes it's functionality I'm trying to update the button text (Like to Liked) without refreshing the page, but problem is that It's updating the every single Like button on the webpage (until I refresh the page) not just the one I clicked on . . .
Here's that success function in AJAX call,
$('.like-click').click(function(e){
e.preventDefault();

var this_ = $(this);
var quesURL = this_.attr('like-href');
$.ajax({
    url: quesURL,
    method: 'GET',
    data: {},
    success: function (data) {
        var like_text = $(data).find('.like-click').html();
        $('.like-click').html(like_text);
    }
})
});

Here's the HTML,
{% for data in datas %}
     ....
     {% if user in Likes %}Liked{% else %}Like{% endif %}
     ....
{% endfor %}

How can I update only the button I clicked not all of them ?
Comment: You have to use `id` instead of `class` here.
Comment: @Mamun Sir, now it's working for first element only . . . ?
Comment: Yes, it will only work for only the matched `id`.
Comment: Post full ajax and html.
Comment: @Mamun Sir, please see the updated the Question . . .
Comment: See the answer. No need to use `id`. Hope that solves your issue.
Answer: Your success function generically updates all class elements ".like-click". If you want to update a single element identify the element in a unique way with an unique id. When clicking emit the id and then when updating filter to only update the element with that id.

Updating Like Button After Click


Can't get items to push to an array

Question:
Possible Duplicate:
Waiting on multiple asynchronous calls to complete before continuing

Update:
Here is the HTML form that lets the user select one or more timelines:
<form>

      <input type="checkbox" id="s-fry" data="stephenfry" />
      Stephen Fry

      <input type="checkbox" id="r-dawkins" data="richarddawkins" />
      Richard Dawkins

      <input type="checkbox" id="s-macfarlane" data="sethmacfarlane" />
      Seth MacFarlane

      <input type="checkbox" id="r-gervais" data="rickygervais" />
      Ricky Gervais

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

And here's the JavaScript
$('input[type=submit]').on('click', function(e){

// prevent default behavior of the submit button
e.preventDefault();

// empty the div with ID of tweets
$('#tweets').empty();

// create an empty ul
var tweetList = $('
');

// create an empty array for the tweets
var returnedTweets = [];

// perform a function on all of the checked boxes
$(':checkbox:checked').each( function(){

var twitterID = $(this).attr('data');

// use the "data" attribute to build the query string for getJSON
$.getJSON( 'http://api.twitter.com/1/statuses/user_timeline/'+twitterID+'.json?callback=?', null, function(data){
    $.each(data, function(i, tweet){
      returnedTweets.push(tweet);
    });
    returnedTweets.sort(function(a,b){ return b.id - a.id; });
    $.each(returnedTweets, function(i, tweet){
      var item  = $('
');
      var name  = $('
').text(tweet.user.name);
      var date  = $('').text(prettyDate(tweet.created_at));
      var img   = $('').attr('src', tweet.user.profile_image_url);
      var msg   = $('
').text(tweet.text);
      item.append(img,name,date,msg);
      tweetList.append(item);
    }); // end of parse
}); // end of getJSON
}); // checkbox.each

$('#tweets').append(tweetList);

function prettyDate(time){
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);

if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;

return day_diff == 0 && (
      diff < 60 && "just now" ||
      diff < 120 && "1 minute ago" ||
      diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
      diff < 7200 && "1 hour ago" ||
      diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
  day_diff == 1 && "Yesterday" ||
  day_diff < 7 && day_diff + " days ago" ||
  day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
} // end of prettyDate

}); // end of "click" function

It is sorting the array before output, but it's not sorting chronologically, as intended. Here is an updated fiddle: http://jsfiddle.net/brianeoneill/FsYKg/
Comment: You are logging the array _before_ it gets filled with data. AJAX is asynchronous - that's why it takes a callback.
Comment: Does `'http://api.twitter.com/1/statuses/user_timeline/'+$(this).attr('data')+'.json?callback=?'` resolve to the string you think it does? Maybe console.log() that string to make sure...
Comment: Yes, it does. I'm able to output the tweets just fine. My problem is with combining multiple feeds and then sorting them.
Comment: Put Consoloe.log before `returnedTweets.push(tweet);`
Comment: @codingbiz or just after... but not outside the AJAX callback.
Comment: ...or try wrapping it in a `.done()` attached to the `.getJSON()`
Comment: @CrayonViolent there are multiple outgoing AJAXes (bad), so merging the promises takes a bit of work (but can be done).
Comment: See the answer to this question http://stackoverflow.com/questions/2768293/waiting-on-multiple-asynchronous-calls-to-complete-before-continuing
Answer: If you want to wait until all callbacks have completed before logging, then try creating an array of Deferred... then when they all have completed, you will have a fully populated list.
http://api.jquery.com/jQuery.when/
Something like this may work:
var returnedTweets = [];
var deferreds = [];

$(':checkbox:checked').each( function(){

    deferreds.push($.getJSON( 'http://api.twitter.com/1/statuses/user_timeline/'+$(this).attr('data')+'.json?callback=?', null, function(data){
        $.each(data, function(i, tweet){
           returnedTweets.push(tweet);
        });
    }));

});

$.when(deferreds).then(
    function () {
       console.log(returnedTweets.length);
    });

Can't get items to push to an array


How can I show that $ \{A \to B, B \to C \} \vdash A \to C $ without using deduction theorem in hilbert-style system??

Question: I've been confused with that for a few days.
The axiomatic system is:

α→(β→α)
α→(β→γ)→((α→β)→(α→γ))
(¬β→¬α)→(α→β)
Comment: Search on this site with keyword Syllogism.
Comment: What proof system are you using?
Comment: how about function composition.
Answer: Here is the sequence:

A->B                          [assumption 1]
B->C                          [assumption 2]
(B->C)->(A->(B->C))           [instance of axiom 1]
A->(B->C)                     [step 2 and step 3, modus ponens]
(A->(B->C))->((A->B)->(A->C)) [instance of axiom 2]
(A->B)->(A->C)                [step 4 and step 5, modus ponens]
A->C                          [step 1 and step 6, modus ponens]
Comment: An additional question is : can I show that {P→(A→B), P→(B→C)}⊢P→(A→C) with a similar sequence?


How do I get the Good Work, Woody achievement?

Question: It says to run into the bottom obstacle three times in a row. I tried running into the lowest zapper I saw as soon as possible three times in a row and that didn't do it. I tried letting missiles hit me as I was walking and that didn't do it.
How do I get this achievement? Am I just missing something really simple?
Answer: You have to die three time by running into a low zapper obstacle without ever flying.
Just start a game and don't press anything (make sure you don't have a head start), most chances the first obstacle you'd hit will be a zapper (missiles don't appear that early), do that three times and the achievement is yours.
Comment: Awesome, it worked. Would've been nice if the achievement text mentioned it had to be the first bottom obstacle or I would've gotten this ages ago!
Answer: Run into the bottom zapper, then play again. Repeat it three more times then congrats. Good Work, Woody.


How to Handle Huge Number of Dropdowns in ASP.NET MVC

Question: We're moving to ASP.NET MVC from Webforms.
Our main page can have up to 130 dropdown lists, each with anywhere from 5 to 50 values in their lists.
In webforms/code behind this is a simple matter. But in MVC, with no server controls in a code behind, it seems like the only way to handle this is to pass in a giant json string indexed on the field name, then relying on jQuery to parse things out.
Any advice?
Comment: There is no code behind because MVC de-couples the UI from the code behind. You can still drop as many dropdowns on a view as you need. Just use your controller and business services to set a property on the model for each of the list of "SelectListItems" you need each drop down to bind to.
Comment: In web forms we were passing more data then mvc, on MVC this is more simple and clean, refer http://stackoverflow.com/questions/14654873/asp-net-mvc-4-viewmodel-with-dropdownlist-data?
Answer: Just to expand a bit on the answer by @fedri .....
Since you have so many dropdowns, I strongly suggest you make use of a viewmodel class to organise the dropdowns. (I won't go into why you have so many dropdowns, as it does seem like an excessive amount, But I guess the design has it's reasons).
Firstly, a viewmodel is simply a class e.g.
public class IndexViewModel
{
    public List<SelectListItem> Dropdown1 { get; set; }

    public string Dropdown1SelectedItem { get; set; }
}

I make use of this viewmodel by passing an instance of it to the view.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var viewModel = new IndexViewModel();

        viewModel.Dropdown1 = new List<SelectListItem>();

        viewModel.Dropdown1.Add(new SelectListItem() { Text = "Item 1", Value = "23" });

        return View(viewModel);
    }
}

@model WebApplication3.Controllers.IndexViewModel

@using (Html.BeginForm())
{
    @Html.DropDownList(nameof(Model.Dropdown1SelectedItem), Model.Dropdown1, "Select item...")
    <input type="submit" value="Save" />
}

When I post back the data, the selected value of Dropdown1 is stored in Dropdown1SelectedItem.
[HttpPost]
public ActionResult Index(IndexViewModel viewModel)
{
    //viewModel.Dropdown1SelectedItem will contain the Value property of the item you selected.

    return View();
}

That's simple enough to get you up and running. The hard part is organising your viewmodel to cater for so many dropdowns, in case you end up getting lost. However, if you name the dropdown properties well enough, then I guess it shouldn't be too bad.
EDIT:
If you must pass dropdown data back via AJAX/jQuery, rather then a from postback, then I can't see how not using a JSON structure to pass the data will work. In that case, I would strongly look at the design and review whether 100+ dropdowns is sensible to be posting back data for in one hit.
Answer: you can add Html helper in View
in controller
public ActionResult Index(string val, bool? inStock)
    {
        var viewModel = new ItemSearchViewModel();
        viewModel.ListOfItems = new SelectList(_service.GetListOfItem(), "ItemID", "ItemName"); //field to use ItemID as value ItemName as text
        return View(viewModel);
    }

in View
@Html.DropDownList("ItemDropdown1", Model.ListOfItems, "Select Item...")

you can look more tutorial for dropdown in here


Can I re-encounter a pokemon that ran away from me?

Question: I had a high level pokemon run away from me when I tried to catch it. Is it possible to re-encounter it in the same place?
If so, how long do I have to wait until I'm able to find it again?
Answer: No, if a Pokémon escapes you can't find that Pokémon ever again with your account. You may, however, find another one of the same species, but there is no telling about time and location.
However, if you escape from the "fight" you will see the Pokémon again right where you found it (unless the spawn timer has expired).
Comment: Note that "escaping" sometimes includes the case where you throw a Pokeball, the servers go kaput, and you reload. If the Pokemon doesn't show up in your journal, you can encounter it again.
Comment: ^ Assuming, of course, that it hasn't despawned in that time - a likely possibility depending on how long it takes to reload the game.
Comment: in addition: It is possible to get the egg for (and hatch) the escaped Pokémon.
Comment: Nope. It's just the same species, but not the very same Pokémon you lost.


AuthorizeView Roles doesn't recognize role even though the code does

Question: I'm trying to set up authorization with Blazor .net core 3.1 and the AuthorizeView Roles doesn't seem to recognize the role that is in the database. On the other hand, if I try to do it in code and I've set up a little message if it finds the role with the user, it finds the role and displays the ""User is a Valid User" message. I'm using this with AzureAd Microsoft authentication and AspNetCore identity package.
Here's the index page code
@page "/"
@using Microsoft.AspNetCore.Authorization;
@using Microsoft.AspNetCore.Identity;
@inject UserManager<IdentityUser> _UserManager
@inject RoleManager<IdentityRole> _RoleManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@attribute [Authorize]

@Message

<AuthorizeView Roles="Users">
    <Authorized>

Youre In!

    </Authorized>
</AuthorizeView>

@code
{
    [CascadingParameter]
    private Task<AuthenticationState> authStateTask { get; set; }

    string USER_ROLE = "Users";

    string CurrentEmail;
    string Message;

    protected override async Task OnInitializedAsync()
    {
        var authState = await authStateTask;
        var CurrentEmail = authState.User.Identity.Name;
        if (CurrentEmail.Contains("@users.com") == true)
        {
            var user = await _UserManager.FindByNameAsync(CurrentEmail);
            if (user == null)
            {
                var newUser = new IdentityUser { UserName = CurrentEmail, Email = CurrentEmail };
                var createResult = await _UserManager.CreateAsync(newUser);
                if (createResult.Succeeded)
                {
                    var roleResult = await _UserManager.AddToRoleAsync(newUser, USER_ROLE);
                    if (roleResult.Succeeded)
                    {
                        Message = ("Good job");
                    }
                }
            }
            else
            {
                var RoleResult = await _UserManager.IsInRoleAsync(user, USER_ROLE);
                if(RoleResult == true)
                {
                    Message = "User is a Valid User";
                }
                else
                {
                    Message = "User is invalid";
                }
            }
        }
    }
}

Here are my services:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options => options.UseSqlite("DataSource=db.db"));

            services.AddDefaultIdentity<IdentityUser>()
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<AppDbContext>();

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();
        }

Comment: Did you ever manage to figure this one out?
Comment: No. I haven't. Tho I found another solution. It's not perfect but it works...
Comment: Sure. I think I followed this one, and it worked for me. https://www.blazorhelpwebsite.com/ViewBlogPost/2
Answer: I do not use Azure for my app, just windows auth.  You have two choices you can use but each requires slightly different uses.
@attribute [Authorize (Roles="DOMAIN\\YourRole"]

Will allow or block the entire page with no custom not authorized view.
<AuthorizeView Roles="YourRole">
<Authorized>If you are in YourRole you are in</Authorized>
<NotAuthorized>If not custom auth message here</NotAuthorized>
</AuthorizeView>

Notice that you must use the domain prefix on the attribute section but do not use it on the authorize view section.


NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until

Question: i am trying to run the below selenium code :
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.behsad.com/nportal/Default.aspx?tabid=55");

        driver.findElement(By.id("dnn_dnnUser_enhancedRegisterLink")).click();

        WebDriverWait wait=new WebDriverWait(driver, 30);
        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(
                                        By.id("dnn_dnnUser_enhancedRegisterLink")));
        element.click();

here is my pom.xml:
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.4.0</version>
</dependency>

and at the end there is the imports of the code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

the code gets stuck in the line:
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(
                                            By.id("dnn_dnnUser_enhancedRegisterLink")));

and it complains with:
java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;

Comment: Possible duplicate of [wait.until(ExpectedConditions) doesnt work any more in selenium](http://stackoverflow.com/questions/42421148/wait-untilexpectedconditions-doesnt-work-any-more-in-selenium)
Answer: I think your problem is in this line of code
WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dnn_dnnUser_enhancedRegisterLink")));

As Wait.until is used to tell your web driver to wait until a certain action to occur which is visibility of The element located by ID = "dnn_dnnUser_enhancedRegisterLink" in your case
but this method Doesn't return a web element object so you can't use it to define a web element
Instead you just need to write :
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dnn_dnnUser_enhancedRegisterLink")));

Answer: Selenium 3.1.0 onwards needs guava 21 for the wait.until method.
Try adding this to your pom, preferable near the top in case another dependency is importing and older version of guava:
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

Answer: It worked with latest jars:
Appium 1.8.1
Java-client 5.0.4
Selenium-java 3.7.1


Image segmentation based upon optical features

Question: I have an image with some texture in a region shown in the first image. I want to segment the image based upon this texture. For this I have extracted feature as shown with blue squares (second image). I want to extract the region bound to the rectangular distribution of the features (shown by red dotted line).
Image 1:

Image 2:

Can somebody help me by suggesting some methodology to pursue this problem. Thanks
Answer: This looks like it might fit the GraphCut image segmentation framework:
You want to find a binary assignment per-pixel (1 - this pixel belongs to the foreground, 0 - the pixel is part of the background). This assignment should include as many "texture locations" as  possible in the foreground, while preserving "smooth boundaries" between foreground and background.
The smoothness requirement prevents your "ideal" assignment to be 1 for the blue dots and zero everywhere else.
Now, how to search for such a binary assignment using Matlab?
Assume you have img of size H-by-W, and you have detected the locations of the texture features and stored these location in a 2-by-n matrix locs.
Setting the per-element cost:
>> bgCost = zeros( H, W );
>> bgCost( [1 H] * (locs-1) + 1 ) = 1000; %// put 1000 penalty for assigning texture dot to foreground
>> fgCost = 10*ones( H, W ); %// assign some positive penalty for assigning non-texture location to FG - prevent an "all foreground" solution.
>> fgCost( [1 H] * (locs-1) + 1 ) = 0;

Optimization:
>> lambda = 5; %// set relative weight between smoothness term and "texture" term
>> gch = GraphCut('open', cat(3, fgCost,bgCost), lambda * [0 1;1 0],
>> [gch BW] = GraphCut('expand', gch ); %//optimization
>> gch = GraphCut('close', gch ); %//cleanup

You should get a nice binary mask in BW
>> figure;imshow( BW, [] );title('binary mask');

There are three parameters you can play with if you are not satisfied with the result BW:

the cost you assign to texture dots in the background (set to 1000 here).
the cost you assign to non-texture pixels in the foreground (set to 10 here).
the relative strength of the smoothness cost lambda.

Try and change these values and see how they influence the resulting mask.
I use this matlab wrapper for GraphCut optimization.
Comment: Nice.  BTW, your Graph Cuts wrapper was very useful in my Ph.D. research.  +1.
Comment: @Shai thanks for the explanation. I'll try to implement this again.
Comment: @rayryeng I'm glad you find it useful :)
Comment: Thanks for your detailed solution. I'm getting error in line
bgCost([1 H] * (locs-1) + 1 ) = 1000; Error: Inner matrix dimensions must agree. Can you tell me the function of this line?
Comment: @user3563929 what error? I assumed `locs` is 2-by-`n` with first row is the row location of each texture dot and the second row is the column location of each dot.
Comment: @user3563929 I assume the dot locations are integer values (rounded to nearest pixel location).
Comment: Yes, dots represent the pixel location only.
Comment: @user3563929 this line `bgCost( [1 H]*(locs-1) + 1 )` is equivalent to `bgCost( sub2ind( [H W], locs(1,:), locs(2,:) ) )` converting `locs` to linear indices into the cost matrix.
Comment: @user3563929 is this solution working for you?
Comment: @Shai, thank you very much. YEs, I could sort out my problem by using your suggested method. Thanks for your kind help.


Pass HashMap via intent as extra

Question: I tried to pass an HashMap via intent from fragment to activity, but without success.
this is my code:
    private HashMap<Integer, JSONObject> myData;

    Intent intent = new Intent(this.getActivity(),MyActivity.class);
    intent.putExtra("myMap", myData);
    startActivity(intent);

and I got a runtimeExeption:
    java.lang.RuntimeException: Parcel: unable to marshal value

I would be happy if someone can help me with that!
I need a way to resolve it, I know that JSONObject is not Serializable.
The value is not a custom object, therfore I can't implement Serializable there.
Thank a lot!
Comment: Possible duplicate of [AndroidRuntime error: Parcel: unable to marshal value](https://stackoverflow.com/questions/3818745/androidruntime-error-parcel-unable-to-marshal-value)
Comment: this is from stacktrace  - `java.lang.RuntimeException: Parcel: unable to marshal value`
Answer: Instead of
HashMap<Integer, JSONObject> myData

you should use
HashMap<Integer, String> myData

And add the items as Strings instead of JSONObject:
myData.put(0, myJsonObject.toString());

then, on your second activity, you create the JSON when needed:
new JSONObject(myData.get(0));

The reason:
JSONObject is not serializable by default but String is (notice it implements  Serializable).

Pass HashMap via intent as extra


Expected path to Sluggable builder in Symfony/Doctrine

Question: The default string normalization (provided by the Doctrine_Inflector::urlize() "sluggifier") isn't suitable for my project, so I need to utilize my own algorithm.
I set my schema up as follows:
MyObject:
  actAs:
    Sluggable:
      fields: [name]
      builder: array('TextUtility', 'normalize')
  columns:
    name: string(255)

And I added my utility class to the lib folder of my project (although I also tried the lib folder of an app) according to some instructions I found in another forum:
<?php
//lib/TextUtility.class.php

class TextUtility {
    public static function normalize($str) {
        /* ... */

        return $str;
    }
}
?>

When I run symfony doctrine:build --all I'm greeted by the following error:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'array('TextUtility', 'normalize')' not found or invalid function name in /symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Template/Listener/Sluggable.php on line 171

I assume I'm just putting my utility in the wrong place and it's not being loaded when needed. Am I putting it in the wrong place? Doctrine's documentation doesn't seem to mention the subject, unless I'm just looking at the wrong page.
Answer: arrays in YAML are defined other way:
MyObject:
  actAs:
    Sluggable:
      builder: [TextUtility, normalize]

Comment: Wow, as obvious as this is, I can't believe I missed it. Thanks!


Error in Dataset$text : object of type 'closure' is not subsettable

Question: I'm trying to perform a sentiment analysis of Tweeter..But at one stage I`ve got

"Error in Dataset$text : object of type 'closure' is not subsettable"
  :

Dataset <- stack
Dataset$text <- as.factor(Dataset$text)
scores <- score.sentiment(Dataset$text, pos.words, neg.words, .progress='text')
write.csv(scores, file=paste(searchterm, '_scores.csv'), row.names=TRUE)

Comment: Please check the `str(Dataset)` I would guess that it would be a `matrix`
Comment: If an object named `Dataset` existed before that assignment of `stack` to that name  , it got wiped out, since `stack` is an R function. So you then tried to apply teh subsetting function "$" to a function and got that error.
Answer: What you are doing is assigning a function to the variable 'Dataset'.
If you type
?stack

in the console you could see what the function does.
For doing your analysis you need data.
The error message means that a function (which is of type closure) is not subsetable.
The dollar sign could be used to subset dataframes.
Read the documentation about dataframes.
?data.frame

First thing you should do is loading the data into your R  environment and assign the data to the variable 'Dataset' and not a function.
Maybe you could tell us what kind of data it is or whether the dataset is available on the net...
If so one could help you much more.
Or if you've already loaded the dataset and you want to stack the dataset and assign it to ne new variable 'Datset'  try:
Dataset <- stack(x)

where you have to replace x by the name of the dataset.
stack is a function which needs to be fed with a dataframe or list (documentation)


MYSQL using AS or other variable to query columns

Question: Running into an issue when querying a live variable.
Sorry for the noob question, but why is this failing? I've tried several variants, etc. as shown. Where am I going wrong?
SET DAYNAME(CURDATE()) = DAY
IF (DAY = 'Monday')
SELECT ID FROM table WHEN Monday = '1';

and
SELECT DAYNAME(CURDATE()) AS Day
WHEN Day = 'Monday'
FROM table WHEN Monday = '1';

Comment: this is not sql and lacks semi-colons
Comment: Please post sample data and expected results.  Do you have multiple columns (Monday-Sunday) and depending on that day name you want to filter on that column?
Comment: I have a monday column with either 0 or 1 in the field. I want to return only results with 1 in the monday column if it is currently monday.

as far as it being sql, SELECT ID, Monday, Value FROM table WHERE Monday = '1'; pulls only the 1's, and has semicolons.
Answer: Based on your comment:

I have a monday column with either 0 or 1 in the field. I want to
  return only results with 1 in the monday column if it is currently
  monday.

Perhaps this is what you're looking for:
select *
from yourtable
where monday = 1 and DAYNAME(CURDATE()) = 'Monday'

Comment: sgeddes, thank you so much. I've been running my head into a wall for the past 4 hours. (and a couple of days mentally). i owe you a beer.


Ajax form not computing GA (_trackEvent)

Question: I have a form at www.ritafischer.com.br/contato.html and I have tried many things but haven't been able to make GA count the event of submitting a form. So far I have the code placed at the summit button with the command =onClick.
the js handling the form is below:
jQuery(document).ready(function(){

$('#contactform').submit(function(){

    var action = $(this).attr('action');

    $("#message").slideUp(750,function() {
    $('#message').hide();

    $('#submit')
        .after('')
        .attr('disabled','disabled');

    $.post(action, {
        name: $('#name').val(),
        email: $('#email').val(),
        phone: $('#phone').val(),
        subject: $('#subject').val(),
        comments: $('#comments').val(),
        verify: $('#verify').val()
    },
        function(data){
            document.getElementById('message').innerHTML = data;
            $('#message').slideDown('slow');
            $('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
            $('#submit').removeAttr('disabled');
            if(data.match('success') != null) $('#contactform').slideUp('slow');

        }
    );

    });

    return false;

});

});

can anyone assist me wit this? it's driving me crazy! heheheh
Comment: What does "GA" mean? *edit* oh - "Google Analytics" ... so what part of this code you posted has anything to do with that?
Comment: Google Analytics, many people use the js to insert the google tracking code, that's why. The form is in Ajax so the user does't leave to any other page.
Comment: I understand that stuff, but I don't see anything in the code you posted that has anything to do with Google Analytics. Maybe I'm just missing something obvious.
Comment: this is what I have on the form code:
Answer: try this
$('#contactform').submit(function(event){
    event.preventDefault()
   _gaq.push(['_trackEvent', 'contato', 'enviar']);

   //other code here
});

Comment: no, i've tried before. it's messing up the code as well. The thank you message show in a different page.
Comment: GA code shouldnt affect your Thank you message... You need to add the event.preventDefault() after the submit line if you dont want a redirect.


How to find minimal set of operations to meet requirements

Question: I think it's easier, if I show my code first.
/* Machine that can add and remove pools to its stack */
public class Machine {
  private final int toolQuantity = 5;
  public boolean addTool(Tool t)    { return true; }
  public boolean removeTool(Tool t) { return true; }
  public boolean processJob(Job j)  { return true; }
}

/* Tool that is needed to process jobs */
class Tool {
}

/* Job that needs specific tools to be processed on machine */
class Job {
  private final List<Tool> needs = Collections.emptyList();
}

interface Command { public void execute(); }

class AddTool implements Command {
  private Machine m;
  private Tool t;
  @Override
  public void execute() { }
  }

class RemoveTool implements Command {
  private Machine m;
  private Tool t;
  @Override
  public void execute() { }
}

Simplyfied code. Aim was just to communicate the idea
So, I have a machine which processes jobs. Jobs need tools (and the tools have an unlimited lifetime). My aim is to find a minimal list of jobs and commands (i. e. instances of AddTool and RemoveTool so that: {"AddTool(x), "job1", AddTool(y), "job2"}), so that a given fixed list of jobs can be processed. Tools that are not needed by a job, can remain on the machine (as long as there is enough place left of course).

I have two approaches:

SIMPLE

Collect requierements from job to job. Since this approach only considers job i and job i + 1. It may not be optimal in cases where machine unloads a tool not needed by job i + 1 but needed by job i + 2. That's an unnecessary cycle of removing and adding (given there was the possibility to remove another not needed tool).

HEURISTIC

Use an heuristic algorith, e. g. simulated annealing, that minimizes the number of commands used.
I would prefer to use a straight forward aproach. But I can't think of another and I guess the simple approach is too unefficient.
So how can I solve my problem? How can it be classified in terms of computer science? I would also appreciate general solutions to these kind of problems that don't specificly handle jobs, machines and tools.
Comment: Hmm, I think I could leave out the part of the question that's about 'classifying the problem in terms of CS'. But I still think it fits the site.
Comment: Just to clarify, the order of the jobs is not decided, so by changing the order you affect the number of actions performed, correct? Is the first job decided or it can be any job in the list?
Comment: While an interesting problem, I think it's outside the scope of Stackoverflow - perhaps http://cstheory.stackexchange.com/ or http://cs.stackexchange.com/ would be better?
Comment: Considering there's a remove tool command, it would be helpful to add the constraint that for a job to be completed there must be all the tools it requires and no other tools.

If there is no such constraint, you'd just need to find the set of tools needed for all jobs and add them.
Comment: No there is no such constraint. The problem is a machine just has place for a certain amount of tools. I modeled that in `toolQuantity`, unused tools can remain on the machine. But the needed tools **must** be on the machine.
Comment: @mwjohnson Yes, you're 100% right. But the order of jobs is fixed. I determined it in a previous step. Look at the comment I gave to kutschkem's answer. This question is only about finding the optimal list of operations.
Answer: This is a hamiltonian path problem, or maybe a Traveling Salesman Problem(if you modify the problem a little bit). Each job needs a certain amount of tools, and you can determine how many commands are needed to get from one job to the other. You want a path through that graph that minimizes the "distance" in terms of additions/removals and visits all nodes/jobs.
Comment: @mike computing the distance between the jobs seems like a planning problem to me. For example, look up http://en.wikipedia.org/wiki/STRIPS . This describes the problem, and you should be able to find algorithms to solve such a problem.
Comment: Finding the optimal sequence of jobs already was a TSP (or hamaltonian path problem... I think TSP is an instance of it). Where I used a heuristic that did compute the 'distance' between jobs. I thought deriving the needed operations could be easier since the list of jobs is already fixed... :/ Thx!
Comment: Since your answer is an acutal solution, I will accept it. But I first want to wait for other approaches, because I originally wanted to avoid using heuristic approaches (and NP-hard problems).


What could be the reason I'm getting the "ERR_SSL_UNRECOGNIZED_NAME_ALER" on my browser while the website works fine from other devices?

Question: I rehosted my website after it was down for a year with a new SSL. I can only assume im getting this error because i used the same computer to do it.
I have reset the SSL cache, deleted browsing history but the website just gives me errors such as stylesheet failed to load becasue of "ERR_SSL_UNRECOGNIZED_NAME_ALER". The website works fine from other devices but on the same pc, it still gives errros on other browsers. What could be a solution.
Answer: The device in question is likely using a different IP to access the site then the other devices. This might be due to the old IP address still being cached in the PC (did you try to reboot?) or even hard coded (did you check hosts file) or it might be an issue of IPv4 vs. IPv6, i.e. your PC accessing the site by IPv6 but the site is only properly setup with IPv4 - which is used by the other systems.
Caching the old IP might also be done by non-local name servers, i.e. you might have a specific name server setup on your PC, it might be a name server on the router or on the ISP. In these cases other devices sharing the same DNS server would have the problem too though. If this is the case you might need to wait until the new DNS settings are sufficiently propagated through the internet, which might take in the worst case a few days but usually only hours.
Comment: Thanks for posting a solution. The IP is not likely a problem because using another device on the same network, the website works. Also the ip isn't static. There's no settings in the host file that relate to ip addresses or re direction. I guess the only thing I can wait for is the proper propagation


Handling events in VB6: Initialize

Question: Here is my question. I have VB6 class FirstClass. In SecondClass i create instance of FirstClass:
WithEvents fClass as FirstClass

...

Set fClass = New FirstClass

Ok. Also in SecondClass I have an event Initialize - this is some event of FirstClass's object (as far as i can understand). But when I paste breakpoint in this event, it doesn't fire. So could you please explain me why I can't go in this event and how the events handling works in VB6 in general.
Please, ask questions if my English isn't good for understanding my thoughts
Update:
Here is property from FirstClass:
Private Property Let IRPCAppMode_Application(RHS As Object)
Const METHOD_NAME As String = "IRPCAppMode_Application" 'DO NOT TRANSLATE
On Error GoTo ErrorHandler
Set mApp = RHS
Set m_objRPCProject = mApp.Project
Set m_objDataSet = m_objRPCProject.CurrentDataSet

RaiseEvent Initialize

...
I know that mApp object sets only in this line of code, that's all. What i can't understand is how Initialize Event rises in SecondClass and how can we set private property outside of class. Calling of Initialize in SecondClass:
Private Sub m_objTestMode_Initialize()
    Const METHOD_NAME As String = "m_objTestMode_Initialize" 'DO NOT TRANSLATE
    On Error GoTo ErrorHandler
    Dim lLoop As Long
    Set mRPCProject = m_objTestMode.Project
    SetupAutoSaveTimer
    SSTab1.Tab = 0
    SSTab2.Tab = 0
    Set m_objToolManager = m_objTestMode.mApp.ToolManager
    Set g_objMonDrives = New clsMonDrives
    Set g_objTrendMonDrives = New clsTrendDrives

....
Comment: Can you add more of the code - in particular the method that you have to handle the event?
Comment: One thing you need to watch out here is that there is a system event on all classes in VB named Initialize, so you may be confusing that event handler with the one you are trying to catch.  The method you should be watching is fClass_Initialize.  Try to set a breakpoint in there and run (F5) and see if you get an event.
Comment: This article gives a good description of the VB6 Event system: http://www.developer.com/net/vb/article.php/1430631/Declaring-and-Raising-Events-in-Visual-Basic-6.htm
Comment: You know, this is hard for me) but i try to explain. FirstClass has a Private Property Let IRPCAppMode_Application(RHS As Object). in this property i have a "RaiseEvent Initialize" line. So I guess if i create an instance of FirstClass in SecondClass and has a handler of Initialize in SecondClass, it fires? Am i right?
Comment: It should, depending on there not being any issues with your code. Post the bit of code that raises the event, and also the method that you that handles the event.
Answer: The Initialize event is already there in your class natively, so if you try to create your own it will be ignored.  Just take your code (get rid of all the custom event code) and put it in the existing Initialize event and you will be fine.
The Initialize event gets fired whenever you create a new instance of your class.  So, if you create an instance of FirstClass with SecondClass you need your Initialize event to go in FirstClass.  That way it will get fired when you create your instance of FirstClass.  So no, SecondClass's Class_Initialize event isn't an event of FirstClass, it's an event of SecondClass.

Handling events in VB6: Initialize


Symfony/Twig: Stop rendering the rest of a template

Question: I've been searching the internet for this, but I can't find anything regarding this.
I'm creating a simple twig template that is going to be used on multiple locations, but requires some variables.
I want to be able to do something like this:
{% if some_variable is not defined %}

Some variable was not defined.

    -- stop rendering the rest of the template --
{% endif %}

{{ some_variable }} is defined here.

The reason I'm asking this is really simple.
I don't want my entire template to be indented in one or more if-statements, since it'll clutter the entire file very easy.
I know the workaround would be to create multiple templates, but multiple files for a simple condition sounds kind of overkill to me.
If this doesn't exist natively, I'm okay creating an extension for this if anyone can tell me how- and if this can be achieved.
Thanks in advance!
P.S. Don't answer with {% else %}, thats exactly the thing I'm trying to avoid here...
Comment: you could create your own extension and impl the php `die` function
Comment: That would stop the execution of the entire application. Sorry, but that's absolutely _not_ what I want ;)
Answer: What you ask for is not natively supported.
To achieve such a thing you would need to go through a lot of trouble.
Twig templates are compiled into PHP, extended by the base template of Twig it self. When looking through in the base template you'll see that eventually the function doDisplay will be called. An example of the contents of this function is as follows
    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "\t

\t\t
\t\t\t
\t\t\t

\t\t\t\t";
        // line 4
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["forms"]) ? $context["forms"] : $this->getContext($context, "forms")), "getTextfield", array(0 => "#label_Quantity#", 1 => "txt_new_quantity", 2 => ((array_key_exists("txt_quantity", $context)) ? (_twig_default_filter((isset($context["txt_quantity"]) ? $context["txt_quantity"] : $this->getContext($context, "txt_quantity")), 1)) : (1)), 3 => ((array_key_exists("errors", $context)) ? (_twig_default_filter((isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors")), "")) : ("")), 4 => "", 5 => "smallinput"), "method"), "html", null, true);
        echo "
\t\t\t

\t\t\t

\t\t\t

\t\t\t\t";
        // line 8
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["forms"]) ? $context["forms"] : $this->getContext($context, "forms")), "getTextfield", array(0 => "#label_Unit_price#", 1 => "txt_new_price_excl", 2 => ((array_key_exists("txt_new_price_excl", $context)) ? (_twig_default_filter((isset($context["txt_new_price_excl"]) ? $context["txt_new_price_excl"] : $this->getContext($context, "txt_new_price_excl")), "")) : ("")), 3 => ((array_key_exists("errors", $context)) ? (_twig_default_filter((isset($context["errors"]) ? $context["errors"] : $this->getContext($context, "errors")), "")) : ("")), 4 => "", 5 => "smallinput"), "method"), "html", null, true);
        echo "";
        echo twig_escape_filter($this->env, getSiteConfigValue("CURRENCY"), "html", null, true);
        echo "
\t\t\t

\t\t\t

\t\t\t

\t\t\t\t";

As you can see the output is sent to the browser immediately (and catched by ob_start in the base template), so even you could exit out of a template the chance exist you'll end up with broken HTML.
TL:DR The only way to achieve such a thing is to override the compiler of twig, which compiles the twig template into PHP, perhaps you could write your own node, as this renders/compiles as well
Comment: Thanks for the quick reply, DarkBee.Guess I'll settle for the workaround then. This indeed sounds like a lot more trouble unfortunately.
Answer: I might be missing something of the original intent, but I found this easy to achieve by extending Twig with a template function that I called cancel
public function cancel($msg = '') {
        throw new Twig\Error\Error("Process cancelled with msg: $msg");
}

As you can see, it simply throws an Exception. Outside the template this is caught and handled.
In the template I write this:
{{ cancel('My reason for cancelling') }}

And, as far as I can tell from my tests, the template processing stops there.
To add the extension follow the normal procedure.
Comment: Then I fail to see how this answers the question. This would mean you could end up with broken HTML, as pointed out in my answer
Comment: Does this still render the rest of the template after the exception was thrown?
Comment: As it says in the answer text, no: "the template processing stops there".
Comment: That's covered in "I might be missing something of the original intent" :-)
Yes you could end up with broken HTML, but Twig is used in many ways, in my case the template is doing entirely different things (kind of executing a low-code program), I am not too bothered with the output being interrupted. I guess the people who upvoted me found uses for it also. I suppose that, like me, they were here for the title of the question, not for the actual details of the question... but it's good that you asked, these comments are helpful to clarify.


Are bathtub sizes the rough in size or the tub interior size?

Question: I am looking at installing a tub and the sizes are not clear what they are.
For example, the "Amiga" bath gives dimensions 72.0″ L x 36.0″ W x 21.0″ H. Is the 6 feet the size of the rough in, or is it somthing else?
In other words if the studs of the wall are 6 feet apart will the bath fit in there?
Answer: All tubs come with "rough in" size specifications which indicate necessary framing/opening dimensions for your unit specs. They can often be found online.
Interestingly, yours says:

Dimensions provided on rough-in diagrams are nominal. Measure your actual unit upon receipt and build according to the actual dimensions.

"
Comment: This is correct. The answer is "it depends". I'd consider building to 72-1/2" and fur down later (on the short wall) for a perfect fit.
Answer: Yes.  In the US bathtubs generally come in 5 foot and 6 foot lengths.  This is the actual length of the unit, and hence the rough in stud to stud distance should be the same.
Comment: In my experience, fitting a thing in a roughed-in opening of exactly the same dimensions is a recipe for frustration. You always want some space for play.
Comment: I agree with @isherwoods comment, some tubs and or surrounds are slightly longer and some slightly shorter. A measurement of the tub + at least 1/4 to 1/2" is what I use you don't want the fit two tight as that can void the warranty on the molded tubs I have installed.


How do I inject a variable into an angularjs filter

Question: I am trying to create a filter that will concatenate a path with an image name.
I store a constant path for images in a value defined on my app like this:
app.value('config', { siteID: '29', apiRoot: 'http://localhost:54003/api', imageRoot: '/Content' });

Now in my filter I want to inject the config object and use it in my filter:
(function () {
var app = angular.module('myApp');
app.filter('imageRoot', ['config', imageRoot]);

function imageRoot(config) {
    return function (imgName,config) {
        return config.imageRoot + '/' + imgName;  // config is undefined
    };
};

})()

Called from html like this:

Answer: Just remove config argument from filter function, because you already have access to the config in the inner scope and specifying it in the function argument will create a new variable for the innerscope with no value assigned to it.
function imageRoot(config) {
    return function (imgName) { //<-- Remove from here
        return config.imageRoot + '/' + imgName;
               //^__ This is already accessible from the outer scope
    };
};


How to really customize an "ubuntu-11.04-alternate-amd64.iso" image?

Question: I have a dream:), I want to customize an "ubuntu-11.04-alternate-amd64.iso" image. What is the best software/solution for it?
I want to customize these things (ALL OF THEM is needed):

Customized package list: I don't need all that comes with the default install, but I have a few thats not inc. in the def. install.

GUI: I don't want a Desktop Environment in it, I only want to use the Openbox WM.

I want a "half-automated" install: the installer only asks for: 1 encryption password + timezone + 1 username/password.
So e.g.: the installer automatically creates an encrypted VolumeGroup with the given password (partitions: 256 MB /boot + VG get's the rest of the place: in the VG: 10 GByte to / and 2 GByte to swap and the rest goes to /home). - I mean with full encryption.

Automatically configure a few apps: e.g.: Google Chrome/Firefox - e.g.: auto install WOT+NoScript in them.

Automatically install & configure: grsecurity; PaX; Pro Police;  DigSig.

Configure in a way that the OS will do all the updates automatically without user interaction.

Set file associations, e.g.: VLC for all the video files, etc.

Install a Local DNS cache + Privoxy proxy & configure them to use as default, e.g.: ns: 127.0.0.1, HTTP/S proxy: 127.0.0.1:8118

Automatically set the iptables Firewall rules that I provide.

Thanks for any help reaching my goal. Have a nice day.
p.s.: All that in one ISO image file (so not like e.g.: boot from a PXE server, i need a custom image in my hand that already contains the needed packages(even extra pack.)  not that it downloads them when installing :P )
Comment: I think this will be a ~~good solution: https://help.ubuntu.com/community/InstallCDCustomization
Comment: Thats a very nice wish list - please add to your question any research that you have done so that any answers dont replicate what you have already tried.
Answer: The last time I looked into this, there were several different methods, each with pros and cons.
I ended up using the Ubuntu port of Red Hat's kickstart. There's a decent GUI tool you can apt-get install: system-config-kickstart. It can definitely do the simple things, like skipping a windowing system or customizing a list of packages to install. It can even do simple partitioning, but I wouldn't count on being able to do LVM, let alone encrypted LVM. See further documentation here: https://help.ubuntu.com/11.04/installation-guide/i386/automatic-install.html
Once you have your ks.cfg, you can either specify it as an HTTP URL when booting, or you can build a new image with genisoimage that has the file at e.g. /preseed/ks.cfg and passes a kernel argument ks=cdrom:/preseed/ks.cfg when booting.
Preseeding the Debian Installer might be the more native way to do it: https://help.ubuntu.com/11.04/installation-guide/i386/appendix-preseed.html
This thread has some other good suggestions, especially FAI: https://serverfault.com/questions/463/how-can-i-configure-unattended-installation-of-ubuntu
P.S.
There are several configuration management systems that may suit your needs if you find that configuring the machine after installation is acceptable. See especially puppet, bcfg2, and chef.
Comment: fai: doesn't supports ext4, uses server to boot custom image
Comment: system-config-kickstart - y, doesn't do lvm/luks
Answer: Have you tried remastersyshttp://www.psychocats.net/ubuntu/backup? You have to make your system just the way you want your custom distro to be and then use remastersys to make your own Ubuntu remix disc.
Comment: remastersys doesn't supports custom rules for lvm/luks?
Answer: Site after site, and application after application... I'm sorry, but for me, all of he above is unnecessary, and will just make things more difficult. The method I prefer for creating a custom LiveCD is to simply mount the image, replicate the contents out, mount the squashfs, replicate the contents into a working directory, chroot in and have a ball. The majority of what you mentioned can be done by editing the default settings for each individual application, usually located under /usr/share/$applicationName/default, or is system wide and therefore has a config in /etc. If you modify everything while chrooted, you can then run mksquashfs on the working directory, replace the squashfs from the original liveCD and create your image. Ubuntu actually has a very comprehensive wiki for this.
https://help.ubuntu.com/community/LiveCDCustomization
Edit: I'm sorry, I just realized that you referenced that article yesterday. I have stepped through it quite a few times, although mainly for the creation of custom portable live usb devices, and I can give you any help you need if you just send me a message.
Answer: I did something like this a while back with SuseStudio. That's just the name of the site, you can use any distro. Check it out. It's been a while since I've been, though.
http://susestudio.com/
Sincerely
Andrew Hauser
Comment: this is askubuntu, i asked about ubuntu, and you're linking suse :) but thx.


Button is not invoking button's css class but it is inheriting css class of parent div

Question: Button is not invoking button's CSS class but it is inheriting CSS class of parent div
Can anyone help?

.sq-ui-ban {
    background-color: #abacb1;
    color: black;
    width: 1000px;
    height: auto;
    overflow: hidden;
    font-style: normal;
    font-family: Calibri;
    font-size: 20px;
    font-weight: normal;
    position: relative;
}

.moreBan {
    position: fixed;
    cursor: pointer;
    font-family: Calibri;
    background: #1c94c4;
    text-align: center;
    color: #FFFFFF;
    border: none;
    font-size: large;
    padding: 5px;
    position: absolute;
    bottom: 0px;
    right: 0px;
}

<button class="moreBan">More</button>

 What is problem in this?
Comment: you DIV tag is not closed,
Comment: I closed it @AdnanAkram
Comment: Now it is showing nothing @AdnanAkram
Comment: need to remove position:absolute; from button or you can remove width from wrapper div ".sq-ui-ban"
Comment: May i know reason for why to remove position:absolute @AdnanAkram
Comment: Ok so a few things: .sq-ui-ban needs to have a set height, right now it's rendering as height:0px and so your .moreBan element which has an absolute position is basically drawing the button outside the view area.

Also you have 2 position properties in .moreBan
Comment: Yeah nice explanation Thank U @TingSun
Comment: Outer div ".sq-ui-ban "  have a width of 1000px  and inner button is position: absolute;  and you have used right so it hide on right side you can use left: 0; instead of right: 0; to see button, and also you have used overflow: hidden on .moreBan, it's better if you use height to on this DIV
Answer: Remove overflow:hidden from .sq-ui-ban and give proper height, width, left and top(Or any position) value to button make your button visible.
Because button parent div height is auto and button is position:absolute so, parent div take no height and overflow:hidden will not allow button to display.

.sq-ui-ban {
    background-color: #abacb1;
    color: black;
    width: 1000px;
    height: auto;
    font-style: normal;
    font-family: Calibri;
    font-size: 20px;
    font-weight: normal;
    position: relative;

}

.moreBan {
    position: fixed;
    cursor: pointer;
    font-family: Calibri;
    background: #1c94c4;
    text-align: center;
    color: #FFFFFF;
    border: none;
    font-size: large;
    padding: 5px;
    position: absolute;
    top: 0px;
    left: 0px;
  height: 50px;
  width: 100px;

}

<button class="moreBan">More</button>


R: Extract controlled vocabulary from character vector

Question: Suppose text data looks like this:
txt <- c("peter likes red", "mary likes green", "bob likes blue")

I want to reduce those string to words from this controlled vocabulary:
voc <- c("peter", "mary", "bob", "red", "green", "blue")

The result should be a vector:
c("peter red", "mary green", "bob blue")

One can use the tm library but that only gives me a dense document term matrix:
foo <- VCorpus(VectorSource(txt))
inspect(DocumentTermMatrix(foo, list(dictionary = voc)))
Non-/sparse entries: 6/12
Sparsity           : 67%
Maximal term length: 5
Weighting          : term frequency (tf)

    Terms
Docs blue bob green mary peter red
   1    0   0     0    0     1   1
   2    0   0     1    1     0   0
   3    1   1     0    0     0   0

How can I get the vector solution with one string per vector element?
The solution should be fast. I'm also a big fan of base R.
EDIT: Comparison of solutions so far
On my data, James' solution is about four times faster than Sotos'. But it runs out of memory when I make the step from length(text) 1k to 10k. Sotos' solution still runs at 10k.
Given that my data has length(txt) ~1M and length(voc) ~5k I estimate that Sotos' solution will take 18 hours to finish, given that it does not run out of memory.
Isn't there anything faster?
Comment: Would a non regex approach suffice for your case? E.g. something like `sapply(strsplit(txt, " ", TRUE), function(x) paste(collapse = " ", x[x %in% voc]))`
Comment: @alexis_laz you win! Your solution finishes in 10 minutes instead of 18 hours. Would you like to create a dedicated answer so I can mark it as the solution?
Answer: A base only method is:
apply(sapply(paste0("\\b",voc,"\\b"), function(x) grepl(x,txt)), 1, function(x) paste(voc[x],collapse=" "))
[1] "peter red"  "mary green" "bob blue"

The sapply part recreates the membership matrix you used the tm package for, while the apply iterates over its rows to pull out the relevant terms from the vocabulary to paste together.
Comment: @Sotos I've fixed it to add word boundaries, so it should work now.
Answer: You can use stringi
library(stringi)
sapply(stri_extract_all_regex(txt, paste0('\\b', voc, collapse = '|', '\\b')), paste, collapse = ' ')
#[1] "peter red"  "mary green" "bob blue"

or full stringi
stri_paste_list(stri_extract_all_regex(txt, paste0('\\b', voc, collapse = '|', '\\b')), sep = ' ')
#[1] "peter red"  "mary green" "bob blue"

Comment: I'm checking your solutions. Note that the result of `txt <- c("peters like reds", "marys like greens", "bobs like blues")` should be empty.
Comment: What do you mean "It should be empty"?
Comment: I mean that your first solution should not extract `peter` from `peters`. In other words, `peters` is not in the controlled vocabulyry, `peter` is.
Comment: The problem with your first solution is that it produces the same output for `txt1 <- c("peter likes red", "mary likes green", "bob likes blue")` and for `txt2 <- c("peters like reds", "marys like greens", "bobs like blues")`. For `txt2` the result should be empty because no word is in the vocabulary. For your second solution I may have to update the `stringi` library cause the `stri_paste_list` function can't be found.
Comment: Do you see what I mean?
Comment: Ok check now. I added boundaries to get exact match so it should work
Comment: `stringi` is really fast actually from my experience


Is there a "folder fingerprint" to detect if a folder's contents have changed between two points in time? I cannot use FileSystemWatcher

Question: I am looking for the fastest way (in C#/ASP.NET) to detect if anything inside a folder has changed between two points in time. I don't need to know the files, total size, or anything else about the folder. I just need to know if anything has changed.
Because I do not have access to the outer scope in which such a folder change detection method would run, I cannot use FileSystemWatcher, which must be disposed when no longer needed (it implements IDisposable and due to the architecture of what I need I am unable to use it in a practical manner).
It would be ideal if there were some kind of "folder fingerprint" GUID that changed if the folder's contents changed. I could then just compare the last fingerprint GUID to the current fingerprint and return true if the two fingerprints were different, indicating something has changed within the folder.
Ideally it would work exactly like the value returned by Assembly.GetEntryAssembly().ManifestModule.ModuleVersionId, which gives you a "fingerprint" GUID of your application's current build, which then allows you to detect if your application has been recompiled between two points in time.
Something like this:
Note: "System.IO.GetFolderFingerprint()" is an imaginary method.
public static class FolderChangeChecker
{
    private const string _path = "c:/path/to/folder";
    private static Guid _originalFingerprint = System.IO.GetFolderFingerprint(_path);
    public static bool FolderHasChanged()
    {
        return System.IO.GetFolderFingerprint(_path) != _originalFingerprint;
    }
}

Please let me know if there is a way to do this quickly.
Comment: There's no such fingerprint managed by the disk system or operating system. You'd have to create a hash on-demand by looking at the data (or at least the metadata) for all of the files and folders in the given folder.
Answer: You could enumerate the files in the directory and build a big string made up of Files' Name, Length, LastWriteTimeUtc.Ticks and create a Hash.
fileStringSb = new StringBuilder();

foreach (var file in files)
{
    var fileInfo = new FileInfo(file);

    fileStringSb .Append(fileInfo.Name);
    fileStringSb .Append(fileInfo.Length.ToString());
    fileStringSb .Append(fileInfo.LastWriteTimeUtc.Ticks.ToString());
}

using (var md5 = System.Security.Cryptography.MD5.Create())
{
    byte[] filesHash = fingerPrint = md5.ComputeHash(Encoding.UTF8.GetBytes(fileStringSb.ToString());
}

Comment: Or do something similar with key properties of the `FileInfo` class. I'm pretty sure that gathering FileInfos is cheaper than enumerating files
Comment: Ya, my original answer just had a remark to encapsulate the actions.  Have updated the answer to use the FileInfo class.  Ta.
Comment: @NeilW I found that concatenating the `DateTime` returned by `File.GetLastWriteTime("c:/path/to/folder")` with the folder path can create a hash that doesn't require enumeration of all the files.
Comment: That makes sense.  An even better solution.
Answer: Advance logging IIS lets you record even file system events that you then can  filter your log file for
advance logging IIS
Comment: "The IIS Advanced Logging is an extension for Internet Information Services (IIS) 7 is no longer available. We recommend Enhanced Logging for IIS 8.5."  https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85
Answer: After some testing, I found that the DateTime returned by System.IO.File.GetLastWriteTime("c:/path/to/folder") is updated every time a file inside the folder is changed. So, this works perfect for what I needed.
To add to Neil W's answer, theoretically, you could create a hash from the concatenation of the last write time and the folder path, that works without having to enumerate all the files inside the folder.
Comment: It's very strange, because in my case the `System.IO.File.GetLastWriteTime()` method was returning a new updated time only when some file was added to or removed from the specified folder. But if file was only updated the  `System.IO.File.GetLastWriteTime()` method returns the same date/time. _The detailed description is in this post:_ [The 'Directory.GetLastWriteTime()' method return the same date/time although a file inside directory is changed](https://stackoverflow.com/q/77351505/6630084). **Therefore, I think the solution provide by @NeilW more correct.**
Comment: @Jackdaw strange, in my environment (windows 11) updating a file also updates the  'GetLastWriteTime' of its folder. I tested it by echoing the DateTime returned by that method to a command prompt every second, and in another window I made changes to a text file located within the folder. Every time I did a save on the text file with Ctrl+S, the DateTime would update
Comment: I'm using Windows 10. Perhaps implementation of the `GetLastWriteTime()` in the Windows 11 and Windows 10 is different.


In R, how can I found the ocurrence of n consecutive numbers in a character string

Question: I have a vector of characters with a fairly repeatable structure that I want to convert to a data.frame.
At the moment I'm marking the separation between columns adding a \t.
One of the fields is a number that at least has 5 characters so I'd like to find where it begins and ends to add a separation mark on both ends.
My vector resembles this one:
v_char <- c(
  "1 Name that may contain 2 number  1234567890 more content later",
  "2 Other name that doesn't have a number  1234567870 more content later"
)

I'd like to obtain this vector:
out_v_char <- c(
  "1 Name that may contain 2 number  \t1234567890\t more content later",
  "2 Other name that doesn't have a number  \t1234567870\t more content later"
)

I haven't been able to find a regex expression to mark the consecutive appearance of numbers and then find their begin and end.
I have reached the position of the blocks as follows but it seems like an overkill:
digits <- gregexpr("[0-9]", v_char)
f_tmp <- function(v) {
  cumsum(c(1L, diff(v) > 1))
}
blocks <- lapply(digits, f_tmp)
f_tmp2 <- function(v, n = 5L) {
  tb <- table(v)
  first_consecutive <- min(names(tb)[tb > n])
  return(c(start = head(which(
    v == first_consecutive
  ), 1L),
  end = tail(which(
    v == first_consecutive
  ), 1L)))
}
positions <- lapply(blocks, f_tmp2)

Comment: If you have multiple such occurrences in `v_char`, you can use `stringr::str_replace_all(v_char, "(\\d{5,})", "\t\\1\t")`
Answer: We can actually just use a simple gsub here
gsub("(\\d{5,})", "\t\\1\t", v_char)

This regular expression matches and captures a sequence of 5 or more ("{5,}") digits ("\d"). Then the gsub takes the captured match ("\1") and adds tabs before and after it before replacing the value in the string.
Comment: Thanks a lot exactly what I needed. I'll accept it when the minimum 10 minutes pass