Stuck in StarCraft II improvement

Question: The problem is that I seem to be stuck in my SCII learning process. I've seen the latest Day9 'Newbie Tuesday' streams and he claims that making workers, not getting supply blocked and making units all the time will improve your game a lot; and it has, but somehow I keep losing a lot, even though I'm always making workers, units and doing my best at not getting supply blocked.
I have a high silver league rank, and I thought doing what day9 says would quickly get me to the gold league, but it's either I'm doing it bad, day9 is not right (which I REALLY doubt) or everyone in my Silver league division is doing what day9 said =P.
Anyway, my actual question is: What is the next step? That is, once I'm used to doing workers, unit and not getting supply blocked all the time, what other things should I concentrate on?
I am a Terran player, and I usually start with an MMM build, and I do variations depending on what I scout on my opponent. Is anyone in my same situation or has been in it?
Thanks in advance.
EDIT:
Here's a replay of my last game. Please be really objective on your critique. If you see I do something really wrong just say it, I won't feel bad or anything. Thanks =).
EDIT:
Also, I know this question seems really specific to me, so if you're in the same situation and feel this might help you please comment on it so the question doesn't end up being closed or anything. Thanks!
Comment: Can you post a couple replays?
Comment: *"Is anyone in my same situation?"* Me. :(
Comment: @tzenes: Will do! Unfortunately I'm at work right now, but will do so as soon as I get home. Thanks.
Comment: @Carlo always trying to help.
Comment: @BlueRaja: lol I hear you, it sucks! Hope the answers to this question help you too.
Comment: Indeed being mid-silver this will highly benefit me as a player.
Comment: Watch your replays and try to see where you could improve and learn from that, but posting a replay could indeed help. You might want to check out replays of pros and see how they are playing... Anyhow, posting a replay for customized advice is always useful. See [my advice for someone else](http://www.sc2replayed.com/forums/sc2replayed-forums/strategy-discussion/360-help-with-terran-i-need-advice) that's close to gold, but that could as well be irrelevant as you might have picked up the necessary things from Day9 already.
Comment: @TomWij: Definitely helps, sometimes I have too much gas but not enough minerals to produce marauders. The rest you suggested I already do (E. G. produce units non-stop, defend expansion, wall in fast, etc). Thanks!
Comment: @Carlo I'll take a look tonight
Comment: @tzenes: I really appreciate it =)
Comment: This recent line of objective questions and answers in regard to specific SC II strategies and the breakdown analysis of what people did wrong (or right!) based on replays is incredibly helpful for those of us that are struggling to learn and even get out of the *cough* bronze league *cough*.  Let's keep these coming, maybe I'll even post one myself.  Also, @tzenes, seriously, you rock.
Comment: Definitely will help, as long as there are more good people willing to tell us what we're doing wrong like @tzenes =P, when I get better I'll definitely try to help out like that too.
Comment: @Carlo did you watch the replay you posted?  Because the reason you lost that game is because you put half your army in the dropship by accident right at the end...  Now I could point out some of the things you did wrong (and I probably will), but it'd be more helpful if you linked me a game where you didn't lose on a mis-click...
Answer: So I'm not going to lie, you lost that game because you mis-clicked half your army into a dropship in the middle of the final battle and it got shot down almost immediately.  I assume you weren't trying to give yourself a handicap there, so let's ignore that and focus on the rest of the game.
Let's focus on why your macro is so bad.
To help you understand why its so bad its important to understand what Macro is:

Macro as a gaming technique is an application of  economic theory; at its simplest it's a distribution of limited resources between necessary avenues.  Consider the simplest example from Starcraft: I have 50 minerals, I can purchase another worker to make minerals for me, or I can build an attack unit and go kill my opponent.  The implied choice here is that I can trade an economic advantage (having and making minerals) for a tactical one (having units).  Since winning usually requires a tactical advantage, at some point a player must make the decision: I'm going to sacrifice my economic advantage for a tactical one.  To the uninitiated this may seem like an easy choice: I'll just build attack units and destroy him if he's building his economy.  However, this sort of theory crafting doesn't hold up.  Once you consider things like: distance, time to kill, etc, you quickly realize that the person with the larger economic advantage can produce a larger army.  How far away, and how long it takes to build an army are important factors in deciding between tactical vs economic advantage.

Now if every decision you make is the difference between an economic and tactical advantage (I'm going to ignore teching for a moment), then we can further provide analysis by saying: Unused tactical advantages are worth less.
In your replay you open up with 1:1:1 and transition into nothing...  Or, maybe it's more accurate to say, you build everything.  Here is a list of what you build (at the 9 minute mark):

2 Barracks (one with Techlab)
1 Factory (with Techlab)
1 Starport (with Reactor)
Engineering Bay
1 Siege Tank
12 Marines
5 Vikings
1 Marauder

At this point the only thing producing units is the Starport.  Out of all these units the only thing you actually use is those 5 Vikings, of which you lose 3 in exchange for 5 probes.  Your problem is that you built a bunch of stuff and then just kind of let it collect dust.
Imagine if I built a Refinery and then didn't put units in it for a minute.  It would sit idle.  Those 75 minerals I used to build the Refinery could have built another Worker, he could have worked for the minute, produced just as much minerals as I spent on him, and I'd still be able to afford the refinery when I needed it.

The first rule of Macro is: build a lot of stuff
The second rule of Macro is: don't build stuff you don't need

You're building stuff you don't need.  You build your Factory early on and even give it a tech lab, and then it sits idle for 10 minutes.  The sole Tank you build out of it in those 10 minutes also sits idle.  You build two Barracks, but only produce a handful of units and then let it sit idle.  You're not building stuff as part of some larger game plan, there is no timing attack you're waiting on, you're just building stuff to build it.  At one point you even build 2 Turrets, despite the fact that you've never scouted a single Starport (and you already have air dominance through Vikings).
Now I understand why you do this, its because the Starcraft single player teaches you to be a bad player.  What the single player does is teach you to build up your defenses.  Trench in, and wait until you have a massive force with which you can move out and win.
Have you ever seen Boxer "trench in"?  Ever seen TLO (NostraDario, the BC rusher himself) build unit producers and just leave them idle for 10 minutes? You know why you don't? because its waste of resources and very bad macro.
Let's take an alternate reality for a second.  In this alternate reality let us pretend there is an evil Carlo, who hates his opponent to death and wants nothing more than to kill him.

This Evil Carlo opens up Reapers!  Why? because he hates his opponent and Reapers are awesome early game against Protoss.  Does he stick his Reapers behind a wall in? No, he rallies them directly to his opponent's mineral line!  But his opponent fights off the Reapers with Stalkers, so Evil Carlo starts building Marauders and Hellions!  That's right, rallied right to his opponent's choke GASP.  And the Marauders fight off the Stalkers while the Hellions slip into the mineral line and toast Probes.  Why? Because Evil Carlo hates Probes.  He hates Probes with a fiery passion which consumes him to the point of rage.  If he saw a Probe get hit by a bus in the middle of the street, he'd run over to it and start kicking it in that one big eye Probes have.  Unfortunately, the Marauders can't hold out against the 4 Warpgate Protoss and Evil Carlo is forced to back off.  But never fear, he's already built a Starport, but instead of swapping for the Reactor he swaps for the techlab!  That's right Banshees.  Evil Carlo is snarling with hatred and anger for his opponent so he produces Banshees which force the Stalkers to run around the base like chickens with their heads cut off.  Evil Carlo laughs at the foolish Stalkers MWAHAAHAHAHAHA.  But meanwhile he's started producing Siege Tanks and Marines (having swapped add-ons), and as soon as the Banshees die he's moving out with Marine/Tank, which he Sieges in his opponents natural!  His opponent hunkers down inside his base, desperately trying to build Immortals.  But what's this?  Evil Carlo has started producing Vikings.  The Vikings fly over the Marine/Tank force providing sight to his range eight billion Siege Tanks.  Evil Carlos' opponent is at a loss for what to do, so he blinks his Stalkers into the middle of the Siege Tanks, only to learn that Evil Carlo's Marines are stimmed! AH THAT'S THE STUFF.
Evil Carlo sounds like quite the player doesn't he?  Here is the big difference between Evil Carlo and real Carlo.  Evil Carlo attacked his opponent with every unit he had.  He constantly put pressure on his opponent and drove his opponent to make poor choices.  Now obviously, if you blindly rally your troops into the enemy base you're not going to have this kind of success, but I'm trying to emphasize a point here: USE YOUR STUFF.  Every building I mentioned in that story you built.  You could have had that army.
If you're not using it, its kind of a waste.  Yes, you need to "build an army," but no one's saying you can't use that army while you're building it.
USE IT
Comment: @tzenes I love it.  Another great read!
Comment: Dude! What a GREAT answer. I loved how you used that Evil Carlo story to explain things, it'll help that stick in my mind and you really gave me a great ROFL haha. Thanks, I'll keep this in mind. I'll definitely take a look at other answers of yours, I'm sure they'll be as helpful. REALLY appreciate it. =)
Comment: "If he saw a Probe get hit by a bus in the middle of the street, he'd run over to it and start kicking it in that one big eye Probes have" brilliant!
Comment: Anyway, I'll definitely be more careful on how I macro. Like day9 said I was just doing units / workers / supply. But I now realized there was no real purpose behind it, or maybe there was one but it was wrong. Thanks for the great answer.
Comment: @Hello, but since he was playing against a Protoss he's kill Probes... not SCVs
Comment: How many times am I going to see that image on stackexchange?
Comment: *nitpick* Terran has SCVs, not Probes.
Comment: this really deserves more upvotes !!!
Answer: The real question to me is why do you lose rather than "why am i not winning?". If you are producing units non stop, never supply blocked with maxed out workers, then either you have a force similar to your opponent or you have more units.
Why can you lose with more units? Maybe your army composition isn't right. Marauders versus speedlings or marines versus tanks. Maybe your units placement isn't optimal when you're fighting. All your units are tight in a choke point while the opponent surrounds the exit. Maybe you build tier1 units and sit on them too long.
The number one reason for losing is because you don't have units anymore while your opponent has plenty. For each game you lose, ask yourself how you lost so many units and how it could have been prevented.
Something I noticed about my lower leagues friends (I'm diamond and most of them are either silver or gold) is that they send their army "into the dark". They just click attack-move, target the opponent's base and pray for the best. Well, this isn't how you win at starcraft!!! Your units are precious, don't let them die for no reason. Something incredibly powerful is to always look at the battle while managing base off-time. When I was beginning, I did the exact opposite. I was looking at my base most of the time while fighting and scouting when I had spare time.
EDIT*
Ok I checked the replay. I would say that your primary mistake was unit composition. You do the reactor switch trick which is great, but you start pumping out vikings. During the whole game, your opponent's only flying units were a dropship and an observer. Vikings are best against air. The landing in the minerals was ok but for an equal amount of minerals/vespene, your could have had a killer marines/marauder/medevacs drop.
Later on your opponent makes mainly stalkers, but you only have a few tanks and some marauders. Your final mistake was to counter immediately after his attack with only marines/marauders. The immortals would shred marauders and stalkers/zealots would deal promptly with remaining marines so you would have needed more firepower to crush the immortals.
As a rule of thumb, in TvP, the vikings are most effective against the colossi but not a "main unit" otherwise (except against very late game carriers).
EDIT 2
I just saw your comment about waiting for colossi. Just a few (4 -5) vikings is plenty to deal with 1-2 colossi since the vikings won't target anything else
Comment: @carlo vikings build faster than colossi, so if you just have 1-2 viks you can take a quick peek to see if he has more.  One of the key to successful countering (and it's really hard to get right) is to not go overkill with the counter units.  If he has 2 colossus, you need maybe 4 vikings, not 12.
Comment: Excellent suggestion. I'd like to think I don't do that, but I might. I usually try to harass / scout at the same time. In this example I saw a robotics facility, so I thought my opponent would go colossi, so I kept producing vikings. But no, apparently he just used it to build an observer. Is there a way, or something that could've told me he wasn't going colossi?
Comment: @carlo you could have looked around for colossi
Comment: @Jason: I thought he had just started because we had a mini-battle just before I saw the robo fac.
Comment: @Davy8: I will definitely keep this in mind. Hope everyone reads it. Thanks.
Answer: Haven't watched the replay yet, but one thing you didn't mention is expanding.  Are you expanding often enough?  I see a lot of people that have a really strong push, but then forget to expand.
Another thing you didn't mention is Day9's biggest thing: keeping money low.  If you're constantly producing stuff and you still have extra resources, you need higher production, make more buildings.
For every game you lose, when watching the replay you should be able to see why you lost.
Did you lose to an early rush?  Did you lose because you didn't expand enough and were mined out?  Did you lose to cloaked units?  Were there any battles you could have microed better?  Watch the units lost metric in the replay.  Are you losing more resources worth of units than your opponent?  That's a sign you're either getting out-microed or you're using the wrong units.
Comment: I did expand after doing some harassment. Also I kept money low, but yeah, I think in this particular games I could've had more units. At some point my macro slipped to around 780 minerals, that was when I sent my army to attack and 2 vikings to harass the mineral line. Other than that I think it didn't slip again. Thanks for the pointers.

Stuck in StarCraft II improvement


SOAP client in Perl

Question: Im trying to "talk" to https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl using Perl and SOAP::Lite.
In PHP its as simple as this:
<?
$client = new SoapClient('https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
$results = $client->doQueryAllSysStatus(array(
    'countryId' => 1,
    'webapiKey' => 'XXXXXX'
));
header('Content-type: text/plain');
var_dump($results);
?>

But with Perl... its not ;).
I wrote this:
use SOAP::Lite;
my $soap = SOAP::Lite->new(proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
my $som = $soap->call('doQueryAllSysStatus', 1, 'XXXXXX');
# tried also this:
# my $som = $soap->call('doQueryAllSysStatus',
#     SOAP::Data->name('countryId')->value(1),
#     SOAP::Data->name('webapiKey')->value('XXXXXX')
# );
die $som->faultstring if ($som->fault);
print $som->result, "\n";

$som->result is empty.
Tried also:
use SOAP::Lite;
my $soap = SOAP::Lite->service('https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
my $r = $soap->doQueryAllSysStatus(1, 'xxxxxx');
print $r, "\n";

... and got Use of uninitialized value $r in print.
Any help would be appreciated...
UPDATE #1:
PHP code outputs this:
object(stdClass)#2 (1) {
  ["sysCountryStatus"]=>
  object(stdClass)#3 (1) {
    ["item"]=>
    object(stdClass)#4 (8) {
      ["countryId"]=>
      int(1)
      ["programVersion"]=>
      string(3) "1.0"
      ["catsVersion"]=>
      string(6) "1.4.94"
      ["apiVersion"]=>
      string(3) "1.0"
      ["attribVersion"]=>
      string(3) "1.0"
      ["formSellVersion"]=>
      string(7) "1.11.91"
      ["siteVersion"]=>
      string(3) "1.0"
      ["verKey"]=>
      int(1505223106)
    }
  }
}

Answer: I found a working solution, so for anybody curious here it is.
I gave up with SOAP::Lite and used XML::Compile::* modules with a little help from HTTP::Tiny.
The code:
use Data::Printer;
use HTTP::Tiny;
use XML::Compile::SOAP11;
use XML::Compile::WSDL11;
use XML::Compile::Transport::SOAPHTTP;

my $wsdlXml = HTTP::Tiny->new->get('https://....')->{content};
my $wsdl    = XML::Compile::WSDL11->new($wsdlXml);

my $response = $wsdl->compileCall('doQueryAllSysStatus')->(
    countryId => 1,
    webapiKey => 'xxxxxx'
);
p $response;

Which prints out:
\ {
    parameters   {
        sysCountryStatus   {
            item   [
                [0] {
                    apiVersion        1.0,
                    attribVersion     1.0,
                    catsVersion       "1.4.94",
                    countryId         1,
                    formSellVersion   "1.11.91",
                    programVersion    1.0,
                    siteVersion       1.0,
                    verKey            1505223106
                }
            ]
        }
    }
}

Yay! ;)
Comment: Nice, glad you got it working.  Seems for some reason SOAP::Lite should've worked, but guess not
Answer: I don't have a web api key so I can't fully test but what about something like this?
#!/usr/bin/perl

use warnings;
use strict;
use SOAP::Lite;

my $soap = SOAP::Lite->new( proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');

my $country = 1;
my $api = 'XXXXX';

my $r = $soap->doQueryAllSysStatus($country,$api);

print $r->result, "\n";

--- UPDATE ---
#!/usr/bin/perl

use warnings;
use strict;
use SOAP::Lite;
use Data::Dumper;

my $soap = SOAP::Lite->new( proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');

my $country = 1;
my $api = 'XXXXX';

my @r = $soap->doQueryAllSysStatus($country,$api);

print Dumper(\@r);

Comment: same as in my examples: result is empty :(
Comment: what's the expected output?
Comment: PHP output added at the bottom of original post
Comment: code above might print out everything but it looks like it's getting data
Comment: yeah, but I have no idea how to get whats important (result of `doQueryAllSysStatus`)...
Comment: Actually its not that simple... But I could provide you with my api key. Is there any way I could send it to you non-publicly?

SOAP client in Perl


Packages installed by one user not available to another in Ubuntu

Question: Possible newbie question here, I'm mainly just a programmer so not so great with Linux. I am installing a couple of packages on a Linux server logged in as one user. When I switch to a different user, these packages are not installed for that user. In the past everything had installed globally for me but doesn't seem so now. What do I have to do to fix this / install globally in the future?
Installations are CUDA and cuDNN installed from debian files from Nvidia's website.
If I'm logged in as the user that I installed them with and I run "nvcc --version" i get the version number back. If I switch to another user and run the same command, I get "The program 'nvcc' is currently not installed."
Comment: What kind of "packages"? installed how?
Comment: That information should go in your question (using the [edit] button) - fwiw it does sound like a difference in the two users' `PATH` variables
Comment: Please also [edit] your question to provide the additional details. Thanks.
Comment: Okay thanks. What can I do to fix this though?
Comment: You should compare contents of `$PATH` variables of both users (`echo $PATH`). Or compare whole `~/.bashrc` and `~/.profile`. Software installed by APT should become available for all users (except some system utilites in `/sbin` or `/usr/sbin`).
Comment: gcc, CUDA, cuDNN and TensorFlow
Comment: _How_ did you install them?
Comment: All from debian files from Nvidia's website
Comment: Also, do you mean a user on that specific server? Or a different user, as in a different account for a VPS hosting service? The latter is probably a separate VM on the host, and therefore will not have packages installed which were installed in another VM.
Comment: Different users on the same server!
Comment: If they are different users on the same server, and you installed debian packages with `sudo dpkg -i *.deb` then they will almost certainly be available for all users on that specific system. If not, then the debian packages are doing very nasty things.
Comment: Also please indicate exactly how you determined that *"these packages are not installed for that user"*. What specific actions / commands did you perform and what was the error that resulted?
Comment: If I'm logged in as the user that I installed them with and I run "nvcc --version" i get the version number back. If I switch to another user and run the same command, I get "The program 'nvcc' is currently not installed."
Comment: Well, `deb` packages don't normally modify a particular user's environment (they have to be installed as `root` anyway). Are you sure you did not take additional configuration steps in the case of the first user (such as making changes to that user's `~/.bashrc` or `~/.profile` files, as suggested by @N0rbert)? if you did, you will either need to make the same changes to the other user's configuration - or find an equivalent system-wide location for them
Answer: You should compare contents of $PATH variables of both users (echo $PATH). Or compare whole ~/.bashrc and ~/.profile.
Software installed by APT should become available for all users (except some system utilities in /sbin or /usr/sbin).


How to close a mongodb python connection?

Question: I'm doing a python script that writes some data to a mongodb.
I need to close the connection and free some resources, when finishing.
How is that done in Python?
Answer: Use close() method on your MongoClient instance:
client = pymongo.MongoClient()

# some code here

client.close()

Cleanup client resources and disconnect from MongoDB.
End all server sessions created by this client by sending one or more endSessions commands.
Close all sockets in the connection pools and stop the monitor threads.
Comment: And also `disconnect ` is no longer available from pymongo 3.x
Comment: @NikhilVJ In the above `answer`, it says: `Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened.`
Comment: in Jupyter Notebook, after .close() I'm still able to query the DB. Is it auto-reconnecting?
Comment: @alecxe, there any way or form of know if the connect daba base closed?
Answer: The safest way to close a pymongo connection would be to use it with 'with':
with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)

Comment: Wouldn't this cause too much traffic when you have a real time application that can perform hundreds of thousands of operations in a matter of minutes?
Answer: Adding to @alexce's answer, it's not always true. If your connection is encrypted, MongoClient won't reconnect:
    def close(self):
        ...
        if self._encrypter:
            # TODO: PYTHON-1921 Encrypted MongoClients cannot be re-opened.
            self._encrypter.close()

also, since version 4.0, after calling close() client won't reconnect in any case.
   def close(self) -> None:
        """Cleanup client resources and disconnect from MongoDB.
        End all server sessions created by this client by sending one or more
        endSessions commands.
        Close all sockets in the connection pools and stop the monitor threads.
        .. versionchanged:: 4.0
           Once closed, the client cannot be used again and any attempt will
           raise :exc:`~pymongo.errors.InvalidOperation`.


How to send requests to api in batches in logic app

Question: I have a logic app in which I create a json request using javascript inline code and send that to an api. The json request might have more than 1000 requests in it. I need to send those requests in the batches of 200 to api. How do I achieve batching in logic app?
Comment: Hi, I'm not so clear about your situation, could you please provide more details of your javascript inline code ? Do you mean separate 1000 json records to five 200 records and use foreach in js inline code to loop the five request ?
Comment: Yes I am doing this currently, var field = Object.keys(workflowContext.trigger.outputs.body.Attributes);
var key = 'key';
var items = workflowContext.trigger.outputs.body.AttributeGroups[key]['Items'].Items;
var ids= [];
for (var i = 0; i <  items.length; i++){
    ids.push(items[i]['Id']['Value'])
}
var ID1 = workflowContext.actions.tag.outputs.body[0].id;
var json = {};
json.records = new Array();
 for(var i in ids)
 {
    json.records.push({
     "attributes" : {
     "Id": ids[i]
     },
    "Property": ID1 ,
          "Type": ids[i]
    });
}
return json;
Comment: I want to generate multiple json array in the sizes of 200
Answer: For this requirement, please refer to the js code below:
//First define a function to do the separate arry operation
function group(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while(index < array.length) {
        newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
}

//Then use the "group(array, subGroupLength)" function to separate your array to multiple 200 records array
var resultArray = group(json.records, 200);

return resultArray;

Afer the code, the resultArray should be like:
[
  [
    {
        "attributes": {
            "Id": ""
        },
        "Property": ID1,
        "Type": ""
    },
    .....
    //200 items
    .....
    {
        "attributes": {
            "Id": ""
        },
        "Property": ID1,
        "Type": ""
    }
  ],
  ....
  //five sub array
  ....
  [
    {
        "attributes": {
            "Id": ""
        },
        "Property": ID1,
        "Type": ""
    },
    .....
    //200 items
    .....
    {
        "attributes": {
            "Id": ""
        },
        "Property": ID1,
        "Type": ""
    }
  ]
]

===============================Update===========================
For your new requirement about give all those sub arrays a name(same name for all sub arrays), I modified the code of function group(array, subGroupLength) like below:
function group(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while(index < array.length) {
        let item = array.slice(index, index += subGroupLength);
        let itemObj = {"subArray": item};
        //newArray.push(array.slice(index, index += subGroupLength));
        newArray.push(itemObj);
    }
    return newArray;
}

In my code, the name for each sub array is subArray. Please check if it meet your requirement.
Comment: Hi @Mm77 I have updated my answer, please take a look.
Comment: Thank you very much for spending the time and looking into it! I did the similar way, I also wanted to give all those sub arrays a name. Same name for all sub arrays, is that possible while creating array?


Selenium Problems in PyCharm -- Everything Seems Properly Updated, Cannot Use Method

Question: I'm on a Mac Mini running Chrome: Version 115.0.5790.114 (Official Build) (arm64) and just downloaded and installed the Chrome Driver which I found here: https://googlechromelabs.github.io/chrome-for-testing/ - the stable version - Mac-Arm64.
I went in and installed and upgraded selenium and pip, and used this terminal command to make chromedriver executable: chmod +x /usr/local/bin/chromedriver.
I've tried two versions of this code to try to pull and print the price element from the website.
**Version 1:  One version pulled up the website but didn't print anything. And the error message I get says that
the WebDriver object has no attribute known as "find_element_by_id"

but apparently this is still a method that functions inside of selenium?
from selenium import webdriver # Importing necessary modules from Selenium
from selenium.webdriver.chrome.options import Options # Importing the Options class from selenium.webdriver.chrome.options

chrome_driver_path = "/Users/myusername/Documents/pythonProject1/chromedriver"

options = Options()
options.executable_path = chrome_driver_path

driver = webdriver.Chrome(options=options)

driver.get("https://www.amazon.com")
chrome_driver_path = "/Users/myusername/Documents/pythonProject1/chromedriver"
driver = webdriver.Chrome(options=options)

driver.get("https://www.amazon.com/Coleshome-Computer-Writing-Workstation-Vintage/dp/B0B6V83D3Q/?_encoding=UTF8&pd_rd_w=dhBqd&content-id=amzn1.sym.5f7e0a27-49c0-47d3-80b2-fd9271d863ca%3Aamzn1.symc.e5c80209-769f-4ade-a325-2eaec14b8e0e&pf_rd_p=5f7e0a27-49c0-47d3-80b2-fd9271d863ca&pf_rd_r=TAX9FJM5MT6DWYCYYMRD&pd_rd_wg=b356N&pd_rd_r=b79c530e-5b03-411d-8957-0ec821732764&ref_=pd_gw_ci_mcx_mr_hp_atf_m")
price = driver.find_element_by_id("priceblock_ourprice")
print(price)

**Version 2:  Doesn't print anything or go to the website and returns an error that says:
'driver = webdriver.Chrome(executable_path=user_path, options=options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path'"

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

user_path = "/Users/user1/Documents/pythonProject1/chromedriver"

options = Options()

driver = webdriver.Chrome(executable_path=user_path, options=options)
driver.get("https://www.amazon.com/Coleshome-Computer-Writing-Workstation-Vintage/dp/B0B6V83D3Q/?_encoding=UTF8&pd_rd_w=dhBqd&content-id=amzn1.sym.5f7e0a27-49c0-47d3-80b2-fd9271d863ca%3Aamzn1.symc.e5c80209-769f-4ade-a325-2eaec14b8e0e&pf_rd_p=5f7e0a27-49c0-47d3-80b2-fd9271d863ca&pf_rd_r=TAX9FJM5MT6DWYCYYMRD&pd_rd_wg=b356N&pd_rd_r=b79c530e-5b03-411d-8957-0ec821732764&ref_=pd_gw_ci_mcx_mr_hp_atf_m")
price = driver.find_element_by_id("priceblock_ourprice")
print(price.text)
driver.quit()

I'd like to be able to receive the price element from the Amazon site, and then print that out following the implementation of this code. Thanks.
Answer: Try Out selenium 4
pip install webdriver-manager==4.0.0
pip install selenium==4.10.0

CODE:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver_path = ChromeDriverManager().install()
print(f"=> Driver Path is: {driver_path}")
s = Service(driver_path)
driver = webdriver.Chrome(service=s)

driver.get("https://www.amazon.com/Coleshome-Computer-Writing-Workstation-Vintage/dp/B0B6V83D3Q/?_encoding=UTF8&pd_rd_w=dhBqd&content-id=amzn1.sym.5f7e0a27-49c0-47d3-80b2-fd9271d863ca%3Aamzn1.symc.e5c80209-769f-4ade-a325-2eaec14b8e0e&pf_rd_p=5f7e0a27-49c0-47d3-80b2-fd9271d863ca&pf_rd_r=TAX9FJM5MT6DWYCYYMRD&pd_rd_wg=b356N&pd_rd_r=b79c530e-5b03-411d-8957-0ec821732764&ref_=pd_gw_ci_mcx_mr_hp_atf_m")

price = driver.find_element(By.XPATH, '//*[@data-cel-widget="corePriceDisplay_desktop_feature_div"]//span[@class="a-price-whole"]').text
print(price)
driver.quit()

OUTPUT:


Why do most microwaves have a "Popcorn" button?

Question: I can't imagine that the usage level of popcorn substantiates its special treatment on a microwave's user interfaces – at least any more emphasis than other common foods.
Removing this (and other presets) would likely clear up the clutter and overall terrible experience that comprises most microwave interfaces. Is this poor UI design, or is there a reason that I'm missing?
Comment: I've never seen a popcorn button. Perhaps it's country-specific.
Comment: And every time I've used a popcorn setting, it burns the popcorn.
Comment: I would actually be surprised if microwaves are used for anything other than popcorn and reheating leftovers for most users.
Comment: Andrew, there's probably a 'reheat lukewarm tea' setting in there though :-)
Comment: I have never used any button other than defrost, the numbers and start. Although I cook popcorn far more often then whatever else is on the buttons.
Comment: That was one thought I had: Perhaps it's a cultural artifact, at least in the States
Comment: Hmmhhh... mine doesn't... I WANT ONE NOW!!!
Comment: @AndrewLeach Some microwaves have default 'quick' settings for pizza, popcorn, potato, etc. eg: http://www.contoure.com/Products/pc/catalog/cmc11040b-control_panel.jpg
Comment: @rk Yes. But the British ones don't include popcorn. http://www.appliance-reviews.co.uk/ProductImages/large/BMM204SS_SS_Microwave_CP1_AR_L.jpg
Comment: @AndrewLeach What can you say but, 'Well, that's why brits aint overweight!' ;)
Comment: @CharlesWesley We mostly use it for porridge. (and leftovers and popcorn of course)
Answer: For the  answer of why a specific button is used for Popcorn, I recommend looking at this discussion from Reddit which has this to say :

Many microwaves nowadays, except for very basic models, will actually
have a humidity sensor built into them. They measure the moisture
content coming off of your food to determine when it's done, because
microwaves work by exciting water molecules in your food. The
different food buttons basically narrow down the expected range of
humidity, because if you think about it, your popcorn has a much
different moisture content than Grandma's turkey dinner.

That said, the microwave has become synonymous with the making of popcorn and since popcorn does have the same content and similar moisture across different brands, setting up a single button to just do the job is just another selling point about what all the Microwave can do and how it can save time.
Interestingly, popcorn was the first item ever heated in the microwave if this quote from History of Popcorn is true

Microwave popcorn -- the very first use of microwave heating in the
1940s -- has already accounted for $240 million in annual U.S. popcorn
sales in the 1990s.

Note : I'll update this answer with a more scientifically driven response if I can find more data to back it up rather than relying on some poster in Reddit.
Comment: While I can't directly refute anything the Reddit poster said, my microwave's Popcorn button, and every other one I've seen including some expensive ones, is just a preset; it sets a power level and a cook time that should be sufficient to pop the corn but not burn it. It's just like the "Pizza", "Entree" and "Hot Drink" buttons. Mine is fancy enough to have settings for not only the 3.5oz "standard" bag, but the 1.75oz "Smart Pop" bag (which, interestingly, specifically tells you on the bag *not* to use the popcorn button, because most 'waves only have a 3.5oz cook time).
Comment: I have seen both types of microwaves. Many do use a sensor and change cooking time based on sensed humidity. Others just preset a time. Mine is currently 10 seconds too long so I have to use the numbers anyways....
Answer: It's a marketing / ease of use feature. People like microwaves because they are quick and simple. They don't want to think. They want to push the button of what they are eating. There's also a baked potato button. And a pizza button. The popcorn will cook it at a different power level. Some microwave ovens use light.


Flutter Reset state of AlertDialog

Question: I have read posts on how to refresh the state in an alertDialog. Using a StateBuilder. I am not sure though why this does not work. THis is how the code looks like.
showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext context) {
    double _progressValue;
    downloadGoogleDriveFile(_files[index].name, _files[index].googleDriveId, _files[index].size,
      (double progress) {
        setState(() {
          _progressValue = progress;
          print('set state progress value='+_progressValue.toString());
        });
      },
      () {
        Navigator.of(context).pop();
      });

    print('progress here=' + _progressValue.toString());

    return AlertDialog(
      title: new Text('Downloading ' + _files[index].name + ' ...'),
      content: StatefulBuilder(
        builder: (BuildContext context,StateSetter setState) {
          return SizedBox(
            height: 30,
            child: LinearProgressIndicator(value: _progressValue),
          );
        },
      ),
    );
  },
);

and my download function looks like this
static Future<void> downloadGoogleDriveFile(String fName, String googleDriveId, String fileSize, Function updateProgress, Function dialogCallback) async {
    var client = GoogleHttpClient(await googleSignInAccount.authHeaders);
    var drive = ga.DriveApi(client);
    ga.Media file = await drive.files.get(googleDriveId, downloadOptions: ga.DownloadOptions.FullMedia);

    final directory = await getExternalStorageDirectory();
    final saveFile = File('${directory.path}/${new DateTime.now().millisecondsSinceEpoch}$fName');
    List<int> dataStore = [];

    file.stream.listen((data) {
      dataStore.insertAll(dataStore.length, data);

      if (updateProgress != null)
        updateProgress((dataStore.length / double.parse(fileSize)) * 100);
    }, onDone: () {
      saveFile.writeAsBytes(dataStore);
      Toast.show('File saved at ${saveFile.path}');

      if (dialogCallback != null)
        dialogCallback();

      if (client != null)
        client.close();
    }, onError: (error) {
      Toast.showError(error.toString());

      if (dialogCallback != null)
        dialogCallback();

      if (client != null)
        client.close();
    });
  }

I think the reason why it does not refresh the alertdialog is because the setState called should be the one inside AlertDialog's StatefulBuilder, am i correct? But i have no idea how to do that. if i place downloadGoogleDriveFile() inside the statefulBuilder's block section it might get called again once setState is called.
Any ideas?
Answer: You can try this using line of code
showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext context) {
    return StatefulBuilder(
      builder: (context,setState){

         double _progressValue;
    downloadGoogleDriveFile(_files[index].name, _files[index].googleDriveId, _files[index].size,
      (double progress) {
        setState(() {
          _progressValue = progress;
          print('set state progress value='+_progressValue.toString());
        });
      },
      () {
        Navigator.of(context).pop();
      });

    print('progress here=' + _progressValue.toString());

        return  AlertDialog(
      title: new Text('Downloading ' + _files[index].name + ' ...'),
      content:  SizedBox(
            height: 30,
            child: LinearProgressIndicator(value: _progressValue),
          ),
    );
      },
    );

  },
);

I Hope will help
Comment: I tried that approach and i get a looping error "This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build)."
Comment: i am using a library called progress dialog that shields this setState() issue within AlertDialog. but i still am interested to get this to work to better understand.

Flutter Reset state of AlertDialog


How can to keep a Python script running on the web server/hosting?

Question: Recently I started working with python and found a cool script to monitor the changes of a website minute after minute and then send an email to one or more people if the content matches what I'm looking for. I know there are better ways to make it, but so far it's working great and i'll share it in case some of you may need:
<code># Import requests (to download the page)
import requests

# Import BeautifulSoup (to parse what we download)
from bs4 import BeautifulSoup

# Import Time (to add a delay between the times the scape runs)
import time

# Import smtplib (to allow us to email)
import smtplib

# This is a pretty simple script. The script downloads the homepage of VentureBeat, and if it finds some text, emails me.
# If it does not find some text, it waits 60 seconds and downloads the homepage again.

# while this is true (it is true by default),
while True:
    # set the url as you please,
    url = "google.com"
    # set the headers like we are a browser,
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36'}
    # download the homepage
    response = requests.get(url, headers=headers)
    # parse the downloaded homepage and grab all text, then,
    soup = BeautifulSoup(response.text, "lxml")

    # if the number of times the word "Google" occurs on the page is less than 1,
    if (str(soup).find("Google") == -1):
        # wait 60 seconds,
        time.sleep(60)
        # continue with the script,
        continue

    # but if the word "Google" occurs any other number of times,
    else:
      #print(soup)
      # create an email message with just a subject line,
      msg = 'Subject: A prefeitura de Ilhabela postou um edital novo, VAI LA VER!'
      # set the 'from' address,
      fromaddr = 'email@example.com'
      # set the 'to' addresses,
      toaddrs  = ['email@example.com']

      # setup the email server,
      server = smtplib.SMTP('smtp.gmail.com', 587)
      server.starttls()
      # add my account login name and password,
      server.login('firstname.lastname@example.com', 'TheTest')

      # Print the email's contents
      print('From: ' + fromaddr)
      print('To: ' + str(toaddrs))
      print('Message: ' + msg)

      # send the email
      server.sendmail(fromaddr, toaddrs, msg)
      # disconnect from the server
      server.quit()

      break

</code>
Now I wonder: how can I keep this scrip running 24/7? Google and Amazon probably have solutions for this, but I'm too unexperienced to find the answers. Could you guys help me with that?
Answer: You can run it on your own computer using Task Scheduler if you're using Windows.
Comment: This is my plan B. I need something on cloud, where the service will be always up and running.
Comment: or crontab in Linux if you use Linux VPS.


online backup solution with api for desktop

Question: I made a small backup application that simply creates an archive out specified files and folders. Now I need an online service to backup that online. Which service can i use that can be integrated into my app ?
Options I considered:
dropbox is ideal, but they have all but abandoned the desktop.
skydrive has no api.
I couldn't find any free reliable backup service that uses ftp .
anything else ? it should provide 1-2 gb of free space and be reasonably reliable.
Thanks
My app is in C#, but can be ported to any other language as well..
Answer: In your case, Amaxon's S3 seems more fitting but that's not free.
Depending on your target audience, you can create a local archive and have that picked up by your regular backup solution. You might try Wuala,or SpiderOak. Expand Wuala by adding your own space. Spideroak is free up to 2GB (more if you invite friends), and also provides a good alternative to Dropbox (if you want to see how to migrate from dropbox to spideroak see my blogpost about that).
Answer: Try box.net, now known as box.com or simply Box
reference: http://developers.box.com/docs


Wordpress Post/Pages redirect when using permalinks and do not when using default settings

Question: I have a webiste on which I use permalinks like /%category%/%postname%/ .
They were working fine a week or two ago. Now when I want to enter a page a get an error telling me that the page is not redirected correctly.
I have no redirects made in my htaccess file. NONE.
If I change the permalinks to default then every page/post works fine.
I do not know what to do. Please help
Here is the .htaccess
<code><ifModule mod_headers.c>
  ExpiresActive On
  # Expires after 1 month
  <filesMatch ".(gif|png|jpg|jpeg|ico|pdf|js|htm|html|txt)$">
    Header set Cache-Control "max-age=2592000"
  </filesMatch>
  # Expires after 1 day
  <filesMatch ".(css)$">
    Header set Cache-Control "max-age=2592000"
  </filesMatch>
</ifModule>
# BEGIN W3TC Browser Cache
<IfModule mod_deflate.c>
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
        AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json
    <IfModule mod_mime.c>
        # DEFLATE by extension
        AddOutputFilter DEFLATE js css htm html xml
    </IfModule>
</IfModule>
# END W3TC Browser Cache
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>
Comment: so everything is fine now? if yes, create short answer what steps you did and accept it, that other visitor will find help in future. BTW it is diffucult to answer why this happened...
Comment: Please edit your question and put all the content you now have in the .htaccess
Comment: I've updated the question with the htaccess code
Comment: What's the error message that you receive? Error page? Blank page? Will the permalinks work if you temporarily disable W3TC?
Comment: Why would I disable W3TC? I did it any way, and still nothing. I've deleted all chaces and deactivated and nothing.
Comment: That was just a test to see if W3TC .htaccess code was the root cause. If it's not then, it's somewhere else. What about the error message?
Comment: My firefox says "The page isn't redirecting properly" and I can see in the console there are many request to my page. the same page every time.
Comment: Does this happens to all pages or just few? also try to disable all plugins (and clear browser cache) and test again.
Comment: If I disable all plugins and enabled them back will all settings in them be saved? be the same? I never did this...
Comment: This happens to all pages and posts, not to categories where i can see the posts titles
Comment: have you always had the ` /%category%/%postname%/` structure or you had some other kind of structure before?
Did you try to go back to the permalink page in the WP-admin and click "save" once again?
Comment: This structure is from the begining and it works fine on other 4 sites with same plugins and settings. I had the same problem on another site or this one I can't remmember and I changed the permalinks settings from /%category%/%postname%/ to default and then back to my settings and that solved the problem, but now Nothing will work.
Comment: I would try to disable all the plugins. If it doesn't work, backup the .htaccess. Then go and remove the permalinks from the wp-admin. Then delete the .htaccess from the server. Then re-enable the permalinks and see if it works. Try also using different browsers, because in some cases browsers may mess with cookies - and try always CTRL+F5 in order to refresh the pages.
Comment: update question with active plugin list, WP version, if you modified WP or not, this will help. Btw if plugins are really good, you can safely turn off/turn on them without loosing, data, but in general it depends. To disable all plugins quickly - rename /wp-content/plugins/ folder to /wp-content/plugins-off/
Comment: UPDATE! I've moved all plugins in a folder called pluginsss and created the original one again, and my permalinks structure works fine. Now I am putting them back one by one to find the one that makes all of those redirects
Comment: @ViliusL I've moved back all my plugins and now my permalink structure still works. I Can not find why that hapened. Now it isn't hapening anymore.
Answer: Very general way to fix wordpress redirect issues: (should work in all cases)

/wp-admin/options-permalink.php Click "save changes". this will refresh WP redirect rules.
check .htaccess, try to comment everything except WP part.
Try to temporary disable plugins. Quick way is to rename wp-content/plugins/ folder, WP will not disable plugins, just will not load them. ATTENTION: do not visit /wp-admin/plugins.php when wp-content/plugins/ is renamed, becouse WP would auto disable them all.
check your themes files, functions.php, try to activate WP another/default theme for test.
If above do not work, download new fresh WP version.

TIP: try to never change files in wp-admin/ or wp-includes/ folder. These gives disaster  in future.


Rodent proof old garage door with uneven driveway

Question: My garage door is old and falling apart, plus the driveway at the threshold is uneven. There are big gaps at either end both along the side and bottom. What is the best way to seal these up? I can't afford a new door right now.

https://photos.app.goo.gl/N6Rkn1BhfdsKCxDW2
https://photos.app.goo.gl/ikK3Ek98pqcMwixR2
Answer: There's a problem. Rodents can get through tiny gaps. Doors generally need gaps around them.
Some ideas -
Remove whatever it is that is attracting rodents. Tidy up the floor. Put edible stuff into metal containers (I use metal bins with metal lids that I weigh down with heavy bricks).
Get a cat and fit a cat-flap. Cats love chasing rodents away.
Graft new wood on around the edges of the doors using glue, dowels, screws or whatever methods and hardware you have to hand. This means taking the doors off after scribing the required shape onto some the donor timber. If an enlarged door would scrape the ground when opening, you'd have to lower the ground or abandon this idea.
Have the door close against a fixed frame. You would probably need a rubber sealing strip or equivalent to close up gaps. Rodents chew through rubber.
Answer: I'd go at it with some blocking and weatherstripping and try to shim the bottom of the door to mate flush with the floor.
There's company that makes specialized rodent proofing materials, you may be able to get by with a door sweep that you put in and adjust it to sit flush to the floor when the door is down.
https://buyxcluder.com/xcluderr-residential-pest-control-door-sweep.html


Module's parameter initialization troubles

Question: I want to have universal function to initialize same module with different parameters. One of them is packed array with size depends on another parameter.  I've tried something like this:
package my_pkg;

    class helper #(
        parameter seed = 0
    );

    static function int GetRand();
        return seed + 10;
    endfunction

    endclass : helper

endpackage : my_pkg

module myModule #(
    parameter myParam = 0
);

    initial begin
        $display("My value = %d", myParam);
    end

endmodule : myModule

module test_class #(
);

    myModule #(
        .myParam(my_pkg::helper #(.seed(5))::GetRand())
    ) i_myModule ();

endmodule : test_class

Vivado synthesis tool builds it without any errors, but Questa Sim doesn't allow to simulate this code. I'm getting following errors:
\*\* Error: ../../../..TEST.sv(54): External function '\<class-spec#1\>::GetRand' may not be used in a constant expression.
\*\* Error: ../../../../TEST.sv(54): The expression for a parameter actual associated with the parameter name ('myParam') for the module instance ('i_myModule') must be constant.

May be some one could advice some workaround for this trouble?
Same code with class without any parameters simulates with no problems. But function stops be universal...
Answer: You can just declare the function in the package without a class:
package my_pkg;

    function int GetRand(int seed);
        return seed + 10;
    endfunction

endpackage : my_pkg

module test_class #();
    myModule #(
        .myParam( my_pkg::GetRand(5) )
    ) i_myModule ();
endmodule : test_class

This compiled for me on questa without errors.


Is every algebra a $\pi$ system (not talking about $\sigma$ algebra)

Question: Is every algebra (or field) a $\pi$ system?
There are a lot of questions asking whether or not $\sigma$ algebra is a $\pi$ system but not for just algebra.
Since algebras are closed in finite intersection, I'm pretty sure that every algebra is a $\pi$ system, but I'm studying alone so I want some confirmation.
Comment: Yes, every algebra is a pi-system.
Answer: An algebra is closed under finite intersections so is a $\pi$-system quite trivially, yes.


Why is this jquery .css style not being applied?

Question: I'm trying to understand why the
 element .css property is not being applied from the Debugger console in Chrome... it says:
Uncaught TypeError: $(...).css is not a function
This is the simple HTML code:

First item

Child list item

Second

Third

Fourth

And the jquery css style:
$("div#container > ul").css('background-color', 'red')
What I'm missing?
Comment: Do you have jquery included in the page?
Comment:
Comment: That probably isn't the only jquery script you're including.
Answer: Did you include jquery? From your html it seems you didn't, in which case it's normal that it doesn't work
Comment: No, I didn't. I thought it wasn't necessary... haven't slept for 2 days... -_-
Comment: This comes from the Developer console of Chrome, I didn't include it but I can do stuff on the Developer console without adding it.
Comment: @Sonhja Please answer the first question you were asked by clav
Answer: As answered by Ace in the accepted answer you did not include jQuery. If you did not include the jQuery file how you got it to work in the first place and never got the error that jQuery is missing and $ sign was resolved for you to get the
 'Uncaught TypeError: $(...).css is not a function'.

Anyways If you want It to work without including jQuery you can use Vanilla JavaScript.
Here is how you can do It:
 var myElement = document.querySelector("#superman");
 myElement.style.backgroundColor = "#D93600";

Comment: Exactly. you're right. your answer is working in my console.


glDrawArrays Access Violation

Question: I am trying to follow [this][1] simple tutorial, but I am getting the following error upon reaching 'glDrawArrays':
Unhandled exception at 0x03D7598E (nvoglv32.dll) in openGLTest.exe: 0xC0000005: Access violation reading location 0x00000000.
void createMesh(void) {
    float* vertices = new float[18];// Amount of vertices

    vertices[0] = -0.5; vertices[1] = -0.5; vertices[2] = 0.0; // Bottom left corner
    vertices[3] = -0.5; vertices[4] = 0.5; vertices[5] = 0.0; // Top left corner
    vertices[6] = 0.5; vertices[7] = 0.5; vertices[8] = 0.0; // Top Right corner

    vertices[9] = 0.5; vertices[10] = -0.5; vertices[11] = 0.0; // Bottom right corner
    vertices[12] = -0.5; vertices[13] = -0.5; vertices[14] = 0.0; // Bottom left corner
    vertices[15] = 0.5; vertices[16] = 0.5; vertices[17] = 0.0; // Top Right corner

    glGenVertexArrays(1, &vaoID[0]); // Create our Vertex Array Object
    glBindVertexArray(vaoID[0]); // Bind our Vertex Array Object so we can use it

    glGenBuffers(1, vboID); // Generate our Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, vboID[0]); // Bind our Vertex Buffer Object
    glBufferData(GL_ARRAY_BUFFER, 18 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW

    glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer

    glEnableVertexAttribArray(0); // Disable our Vertex Array Object
    glBindVertexArray(0); // Disable our Vertex Buffer Object

    delete[] vertices; // Delete our vertices from memory

    glBindVertexArray(vaoID[0]); // Bind our Vertex Array Object

    glDrawArrays(GL_TRIANGLES, 0, 6); // Draw our square

    glBindVertexArray(0); // Unbind our Vertex Array Object
}

I am at a loss as to what is causing it as the tutorial is the same!
Comment: I'm still looking over the code, but on a hunch, what happens if you remove `delete[] vertices;`?
Comment: I removed it, but the same access violation still occurs.
Comment: Okay. OpenGL does funny things behind the scenes, so it's good to rule out stuff like that.
Comment: You may wish to post the whole code, including the main method. The initGL() function looks a bit suspicious, but I can't know that for certain unless I can see how it gets called from the main function.
Comment: I experimented with moving the glewInit around, but to no avail. The code is posted above, minus the methods that aren't anything to do with OpenGL. This simple box drawing part is the only OpenGL issue that seems to show up, as I can draw points and lines with no issues.
For some insight, this is what works: EXAMPLE VIDEO
Comment: When you call glDrawArrays here have you bound a shader? This function looks like it shouldn't be doing any rendering, since it's called `createMesh`. Are you sure all other required state is set up correctly when `glDrawArrays` is called?
Answer: When dealing with OpenGL, an Access Violation reading location 0 typically means that your hooks into the OpenGL API are not properly established. Is GLEW properly set up in your code? Did you call glewInit() and verify that the result is GL_TRUE? Is glewInit() being called before or after you make the context current? Verify all of these things, and it should resolve the issue.
Comment: I am calling glewInit() in my 'int InitGL(GLvoid)' method that sets up things such as 'glShadeModel(GL_SMOOTH)' or 'glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)'. That's not too early is it? It gives GLEW_OK and doesn't seem to drop into the error check. Updated main question to show this.
Answer: After much experimentation I fixed this issue by changing the first line to:
float vertices[18];

and removing:
delete[] vertices;

Comment: You may not have fixed it but instead made the bug harder to reproduce.
Answer: I had the same error when i used glDraw. I fixed it by binding the VertexArray first then the IndexBuffer

glDrawArrays Access Violation


What's the practical difference between "latex" and "acrylic" water dispersion paint?

Question: I see lots of water dispersion paints in shops and they usually come in two flavors - "latex" and "acrylic". The application range and procedure seem the same, they are all relatively safe, don't emit anything toxic while drying, prices are more or less the same.
What's the practical difference and how do I choose?
Comment: The ratio of Polyvinyl Acetate to Acrylic Resin contained in the paint.
Answer: There actually is no difference between latex and acrylic paints because there is no latex in latex paints. Let me explain. All water based paints today are referred to as "latex", even though there is absolutely no latex rubber in the formula. Latex has become a generic label. The stain, water resistance and covering capabilities are achieved by using acrylic resins or vinyl . Better quality paints have more acrylic resins than vinyl.  Paints with a higher percentage of acrylic resin cost more. Vinyl is much cheaper than acrylic and is often used to mix with the acrylic to keep the cost of the paint lower. If you have special needs that may require a superior or better adapted product, the best advise is to go to a professional paint store and discuss your situation with someone that can explain the chemistry and applications of better products.
Comment: The irony is the technical explanation you provide greatly outperforms what any salesperson in our region can provide - the most clever though they have is "emmm, this one is two dollars per liter, it's emmm, maybe good, that one is ten dollars per liter, it's emmm, much better". It was very funny when I bought cheap paint, failed miserably *because I didn't know I had to use a primer* and then they said "come on, that's cheap paint, buy [the ten dollars per liter] and it'll be great".
Comment: Hear your pain. Paint is chemistry and having a competent paint supplier with trained knowledgeable sales people is priceless.  My grandfather and uncles owned a Keystone/Valspar custom paint store and were painting contractors for over 40 years. No substitute for experience I guess.
Comment: An entire different conversation about paint is pigment quality. Coverage is greatly effected by the amount of pigments used. Again, cheap paints are light on pigments, better paints have much higher and better quality pigments. The actual weight of the paint is different as well. There are several factors that effect paint quality and price. Would be a very long study, but you can read lots of good articles online.
Comment: +1 because both Acrylic Latex and Latex paint are emulsions in water and water cleanup capable. The difference is the ratio of Acrylic Polymer to Vinyl Polymer. Acrylic resin is longer lasting and the higher the Acryl content, the more expensive the paint. They are both "chemical based" as I've not come across any Acrylic Trees or Vinyl Trees in the wild (given genetic engineering, maybe a future possibility). Acrylic resin is also soluble in other mediums and therefore can also be formulated as an "oil based paint".
Comment: Acrylic paint IS soluble ... I use it all the time rather than oil for art.
Comment: -1 because of first line. There is a difference. Latex is water soluble, acrrylic is not. There are differences in weathering.  Everything else you said may be entirely accurate, but there is a difference.
Comment: @Chris: Practicaly speaking, acrylic is included in most latex paints. I was referring to the amount (%) and quality. The resins and vinyl are not water soluble, but the formula is commonly refereed to as latex and is water clean=up as opposed to having to use mineral spirits. True 100% latex is rubber and is not in itself water soluble either. The chemicals in the paints are in  suspension, and obviously are not water soluble once dry.
Comment: What you do not answer is what the problem is for those who are allergic to the product and the off gassing of the product. So the warning should be to those who experience breathing products around the paints is this, no VOC is also a dangerous product to be exposed to when you have known reactions to the fumes of these products.
Answer: You almost answered your own question, in terms of practicality. Acrylic paints are more durable, resilient and more expensive paints. They thin with water, clean up with water, just as latex (as in the house paint sold by the gallon at Home Depot or Lowes) but just as mentioned by others, latex paints are mixed down using vinyls, making them more porous and less durable.
Many commercial paints make claims about durability and performance compared to other latex based paints, but will never compare their products to an acrylic or oil based paint. The main difference is the outcome of the different applied paints. Oil has the most durable finish, most resistant, while also being the least flexible; acrylic is next, then latex.
You may have noted differences in prices between the different bases for latex, especially between that of base flat, and high gloss bases. High gloss contains more polymers, more acrylic, and simply put has more "in it" which makes it a high gloss. Adding durability costs money, and it usually reflects the things a company has to put into the paint in order to raise the quality. There are more ways to add "durability" today than simply raising the % of acrylic in the mix.
Answer: There are many water based "100% acrylic" "Latex" paints. I use them in the form of exterior porch and floor enamel. I don't really know what 100% acrylic means, except it's more expensive, and, in my experience, higher quality - more durable, lasts longer, sticks better.


Python Parsing - Multiple Emails in One Text File

Question: I receive similar emails from multiple senders and use regular expressions m and n below to pull out needed strings. That part is working fine.
Regular expression o however is what has me confused. The text file I am reading is a combination of 9 email messages saved to one text file and opened in Python as a string. Original Sender (regex o) occurs at the beginning of each new message in the file (9 times)
I want to write the same Original Sender after each CUSIP and NAME found until a different Original Sender is matched.
I am using xlwt3 and wincom32.
Sample from the text file with combined emails which is very standard:
--- Original Sender: TOM MADEUPNAME, SOME BANK, N. ---
----- Original Message -----
From: TOM MADEUPNAME (SOME BANK, N.)
To: BOB THISISMYEMAIL (XYZ INVESTMENTS, INC)
At:  8/31  8:53:25
**Offerings**

Mezz ReRemics
Cusip      Description       Original Current Cashflow Collat Offering
05531UAB6  BCAP 2009-RR5 1A2   18,745  18,745 Snr Sup  Fxd      45.000

Prime/Alt-A Fixed
Cusip      Description       Original Current Cashflow Collat Offering
059487AE8  BOAA 2006-6 CB5     25,940  14,350 Seq      Fxd      83.000
12544XAX3  CWHL 2007-9 A13     10,190  10,190 Ssnr Nas Fxd      92.500
17312XAJ3  CMSI 2007-4 1A9      2,871   2,741 Spr Snr  Fxd      86.000

--- Original Sender: JOE MADEUPNAME, EUROPEAN BANK SECURI ---
----- Original Message -----
From: JOE MADEUPNAME (EUROPEAN BANK SECURI)
To: BOB THISISMYEMAIL (XYZ INVESTMENTS, INC)
At:  8/31  8:20:16

8-31-2011

Alt-A Fixed
Bond            O/F    C/F    Cpn  FICO CAL WALB  60+    Notes             Offer
CSMC 06-9 7A1   25.00  11.97  L+45  728  26  578  35.21  FLT,AS,0.0%       50-00
LXS 07-10H 2A1  68.26  34.01  L+16  744   6  125  33.98  SS,9.57%          42-00
CSMC 06-7 9A1   15.00   7.81  L+30  688   5  198  46.46  SS,0.0%           29-16

Prime Hybrid
Bond            O/F     C/F   Cpn  FICO CAL WALB  60+    Notes             Offer
SARM 05-18 6A1  14.56   6.01  2.58  730  46  432  15.87  SEA,SS,5/1,12.3%  78-00

Alt-A Hybrid
Bond            O/F    C/F    Cpn  FICO CAL WALB  60+    Notes             Offer
ARMT 05-12 2A1  23.78  10.71  3.07  712  48  556  35.32  SS,5/1,4.9%       *SOLD

Option Arm
Bond                O/F    C/F   Cpn  FICO CAL WALB  60+    Notes          Offer
DBALT 07-OA4 1A1B  10.00   7.25  L+13  716  63  562  47.17  SS,OC,42.2%    64-16
--------------------------------------------------------------------------------------

Updated - working
count_cusip = 0
count_name = 0
count_sender = 0
cur_sender = ''
for line in lines:

    o = re.search(r"Original Sender:\s\b\w+\s\w+", line)
    if o:
        count_sender += 1
        ws.write(count_sender,2,o.group(0))
        ws.write(count_sender,2,cur_sender)
        cur_sender = o.group(0)

    m = re.search('[0-9]{3}[a-zA-Z0-9]{6}', line)
    if m:
        count_cusip += 1
        ws.write(count_cusip,0,m.group(0))
        ws.write(count_cusip,2,cur_sender)

    n = re.search('[A-Z]{3,5}\s[0-9]{1,4}\D{1,3}\S{1,3}\s{1,2}\w+', line)
    if n:
        count_name += 1
        ws.write(count_name,1,n.group(0))
        ws.write(count_cusip,2,cur_sender)

        o = re.search(r"Original Sender:\s\b\w+\s\w+", line)
        if o:
            cur_sender = o.group(0)

        ws.write(count_name,2,cur_sender)

Updated Output - as desired.
CUSIP   Bond Name           Original Sender
00442PAD2   ACE 2006-OP1 A2B        Original Sender: Nick Madeupname
12557YAE7   ARMT 05-12 2A1          Original Sender: Bobby Madeupname
39153VAT1   CSMC 06-9 7A1           Original Sender: Bobby Madeupname
05377RAE4   LXS 07-10H 2A1          Original Sender: Jane Madeupname
02005HAF0   CSMC 06-7 9A1           Original Sender: Jane Madeupname

Comment: it would help a great deal if you could post an example of the input you are trying to process.  You should change names, subject lines, and content of the emails to preserve privacy, but leave the general format intact so we can see what you are trying to parse.
Comment: What is the purpose of the `\b` in your last regex?  It seems to me you are looking for exactly one whitespace character after the colon, after which at least one alphanumeric must appear.  I would think this is, by definition, a word boundary.
Comment: what is ws.write()?  Are you writing to a spreadsheet using `xlwt` or what?
Answer: Your question isn't completely clear since you didn't show an output sample, but here's an educated guess:
count_cusip = 0
count_name = 0
count_sender = 0
cur_sender = ''
for line in lines:

    m = re.search('[0-9]{3}[a-zA-Z0-9]{6}', line)
    if m:
        count_cusip += 1
        ws.write(count_cusip,0,m.group(0))
        ws.write(count_cusip,2,cur_sender)

    n = re.search('[A-Z]{3,5}\s[0-9]{1,4}\D{1,3}\S{1,3}\s{1,2}\w+', line)
    if n:
        count_name += 1
        ws.write(count_name,1,n.group(0))
        ws.write(count_name,2,cur_sender)

    o = re.search(r"Original Sender:\s\b\w+\s\w+", line)
    if o:
        count_sender += 1
        cur_sender = o.group(0)

Rather than writing the Original Sender when encountered, you need to save it and write the current value for each cusip and name.
Comment: I posted the output to help. Seems this code produces an overwrite error.  Traceback (most recent call last):
     ws.write(count_sender,5,cur_sender)
  File "C:\Python31\lib\site-packages\xlwt3\worksheet.py", line 961, in write
    self.row(r).write(c, label, style)
  File "C:\Python31\lib\site-packages\xlwt3\row.py", line 226, in write
    StrCell(self.__idx, col, style_index, self.__parent_wb.add_str(label))
  File "C:\Python31\lib\site-packages\xlwt3\row.py", line 145, in insert_cell
    raise Exception(msg) Exception: Attempt to overwrite cell: sheetname='Bond List' rowx=1 colx=5
Comment: Without knowing what ws.write does and the context in which you're running, it's not possible to figure out what you need to do.  The output you show clearly doesn't reflect what ws.write is doing.
Comment: ws.write comes from xlwt and writes to cells in excel. ws.write's format is (row,column,regex match). The for loop reads the text file line by line and the first pass for regex m matches a cusip in the string and writes that via ws.write(1,0,'929766LY7') to excel, as well regex n matches a bond_name and it is put to excel via ws.write(1,1,'WBMCMT 2003-C8 A4'). Am I helping?
Comment: @dadashek: OK, I updated the code to put the current original sender in column 3 on each line.  Your example still really doesn't make sense: why is Original Sender empty starting with FAIRF?
Answer: Any chance you can change the format to something recognized by the mailbox module in the standard library.  Then you could let that module handle all the parsing.


How to fix hairline crack in brick on exterior of house

Question: I have a cracked brick outside my window, and it looks like the crack runs down the mortar to just under the window ledge.
The piece of the brick that cracked off is movable (ever so slightly) if I apply pressure, so it doesn't appear that the mortar on the top or bottom is adhered to it.
I can't, however, pull it out with my fingers, additionally the brick below it is immovable.
My main concern with this is water damage over time, getting into the crack or above/below it.
I suspect the most permanent solution is to remove the entire brick and and redo the mortar around it, tracing it down the crack.  However, I'd like a less costly and time-intensive solution, if possible.
I've looked into injecting (via syringe) some epoxy, however there's a lot of different products and I have no idea what to pick, if this is even a viable solution.
What is a good cost-effective way of dealing with this cracked brick?
Answer: Injecting epoxy is a viable solution. In this case there are not significant differences in various epoxies. Any should work.
A thicker/faster-curing epoxy might stay in the crack better, but those qualities also might make it stay in the syringe better too, so give that some thought.


Need help with restaurant menu customization ui and ux

Question: for the app that I'm working on, a restaurant owner/manager has the option to customize their menu. The flow is that:

The system suggests a list of items that can be served by a restaurant. This list will be large (say ~1000), so will be searchable. The manager can only pick as many items from this list.
Each item of this list has: Name, Category, Tags and Image.
When the manager clicks on one of these items, they need to enter some additional info about the item - like, Price, Discounts, and ServingHours(one or many); before the item gets added to their menu.
Ideally the manager should be able to view their current menu as they update (add/remove items) it.

My Current Approach:
The UI that I've in mind is: having two sections side-by-side - the left one, for restaurant's current menu; and the left one to show list of available items. The right section has a saerch bar on top, and the items are shown as cards. On clicking an item from the right section, the manager is presented with a popup with a form to enter additional fields, after which they can click on a SAVE button to close the popup and add this item to their menu.
Problem:
The user has to scroll quite a bit on the right side, and the flow does not seem very fluent which in turn makes the experience feel tedious and unpleasant, especially when it needs to be repeated for more than a few times.
Any suggestions in UI/UX to make this experience smoother and pleasant ?
PS: This ui is for a web app to be used on a desktop and large screens, which means a typical desktop sized screen space is available.
Thanks.

Edit: Added a hand-drawn mockup for reference of current approach.
Comment: @locationunknown updated question with a hand-drawn mockup. Hope that helps.
Comment: @jazZRo I'm sorry, if I sounded otherwise but "out of the box" ideas is exactly what I'm looking for. The current approach- it works, but it feels like it can definitely be improved - especially the no. of clicks and scrolling required to select and add an item to the menu. And, probably because I'm a backend developer myself, I'm out of ideas to come up with a better UX than this. So, any ideas regarding UI modifications and changes, are really appreciated.
Comment: Can you show us some mock-ups of what you thought of so far. It is hard to get the idea from text alone.
Comment: Is the current menu on the left side really necessary? If the searched (or filtered) items show whether they are in the current menu or not, would that be sufficient?
Comment: The right list is in itself too long, merging it with selected item list on left ... would cause even more scrolling and confusion; don't you think ?
Comment: @MrClan My question wasn't rhetorical, I asked it to get an idea of how much you're stuck with this concept or if there is some space left for out-of-the-box thinking. I also hoped it would invite you to add more details about the context and usage.
Answer: It is a good thing you mentioned that your users have large screens. But what happens to those who don't? How responsive is the solution? The first thing I would do is find 5 users and test it out. If they understand this layout and complete tasks successfully then develop it. I would like to give more insight but the problem is that I am not one of your users so you will have to test with them.
Answer: Does the list really need to be 1000 items long? Can it be categorized in some way? Assuming this is food, having categories like italian, chinese, american, healthy, hearty, vegan, vegetarian, keto, high protein, etc. can make it so the user doesn't have to scroll through 1000+ items at one time. It keeps things organized and minimizes scrolling. Also perhaps an option to "hide" or otherwise shrink the left current column as it seems most of the work is being done in the right list, while the left list is mainly visual. This creates more space for your right column, again, minimizing scrolling since you have more horizontal space.


Remove Ubuntu from a MacBook and put OS X back on

Question: I bought a MacBook off eBay, thinking it would have OS X on it, but it didn't. It came with Ubuntu instead. I think it is a 2006 model or a 2007 model. I want to know how to put OS X back on it as I don't like Ubuntu.
Comment: How do you install OSX onto a machine? I would assume you already know how to do that?!
Answer: This has nothing to do with Ubuntu or Linux. To remove an operating system, you just format the whole drive and install the new operating system over it.
If you are lucky, it's a dual boot computer. Hold the X Button while booting to boot into OSX if it is available. From there you can remove Ubuntu (to get help on this see https://apple.stackexchange.com/). If you still can not boot OSX, read further.
Since you bought a device, but apparently no license of OSX (you really got no disc?), you'll have to buy it somehow or use the help of a friend, as amanthethy wrote in his answer. This is an unusual case. Normally, the OS is preinstalled and it makes no sense to remove it, since if you buy a new device, the OS comes with it.
If you have no disc or USB drive of osx
Ask a friend with OSX to create you a copy (like amanthethy wrote) or buy it:
Here you can buy Snow Leopard, which is the oldest I found in the store. You can freely upgrade the OS if the device supports it. Make sure that your device is supported by this version of OSX first.
http://store.apple.com/us/product/MC573Z/A/mac-os-x-106-snow-leopard
How to install
To install the OS, just insert the disc, choose the disc tool in settings and format the whole drive. Then choose to install it. It's pretty straight forward.
For better help on OSX
Please note: The correct place to ask detailed osx questions is here:
https://apple.stackexchange.com/
Answer: Reinstall OS X Snow Leopard from the OS X Snow Leopard install disc. If you don't have one, you'll have to find someone who does and get them to lend it to you. I think Apple stopped making them (the discs) about 4 years ago.
If you can't get a copy of the Snow Leopard install disc, you can try installing a newer version of OS X USB. Google how to make a bootable OS X USB. You'll need a working Mac for this as you need to download the OS X install files from the Apple App Store and make the USB install stick with tools that run on OS X. Your MacBook may be too old to run the newer versions thought. You'll have to do some research on your own, bud (ie. Google "Can my MACMODEL# run OS X
VERSIONYOUWANTTORUN").
This question isn't Ubuntu related. You won't find much more help than this here.
Comment: Doesn't the new bootable usb device contain the same license as the computer the iso downloaded and therefore can probably not easily installed on a second computer? I'm not sure.
Comment: Mac doesn't have licensing BS with OS X like MS does with Windows. Download once, deploy a million times if you want.

http://apple.stackexchange.com/questions/17884/can-i-use-the-new-lion-os-x-license-on-two-machines-or-do-i-have-to-buy-one-for
Comment: Interesting, thank you. Makes sense, now that I think about it.
Answer: Unlike more modern Macs, the 2006/2007 models came with an installation CD/DVD so your best bet is to find a friend with a copy of OSX 10.4 Tiger, OSX 10.5, Leopard or OSX 10.6 Snow Leopard which is the latest system these models will run. You may find them on eBay or at a Mac store such as OWC Macsales. Once you have an installation disc, insert it into the MacBook's optical drive, reboot holding down the C key. When that's opened, select Disk Utility from the tools, and reformat and partition the drive, then the installation should be straightforward.


Distance and uniqueness for projections

Question: Let $\mathbb{W}$ be a subspace of the finite-dimensional inner product space $\mathbb{V}$, and let $\overrightarrow v \in V$. Show that $P_{W}(\overrightarrow v)$ is the unique closest vector in $\mathbb{W}$ to $\overrightarrow v$.
Uniqueness is easy to show by constructing any basis for $\mathbb{W}$, by definition any vector in $\mathbb{W}$ can be uniquely written as a linear combination of a basis. I'm having a hard time to show it is the closest vector:
$||\overrightarrow v-P_{W}(\overrightarrow v)||=Proj_{W^{\perp}}(\overrightarrow v)$
I then have to take an arbitrary vector in $\mathbb{W}$ and show that $||\overrightarrow v-\overrightarrow w||$ ($\overrightarrow w \in \mathbb{W}$) is less or equal to $Proj_{W^{\perp}}(\overrightarrow v)$. Any hints on how to go about it?
Comment: What is your definition of projection?
Answer: We need:
Claim.- Let $\;w_0\in W\;$ , then for all $\;w\in W\;$ we have that
$$\;v-w_0\perp W\;\implies\;\left\|v-w_0\right\|\le\left\|v-w\right\| $$
Proof: For any $\;w\in W\;$ we have
$$\left\|v-w\right\|^2=\left\|v-w_0+w_0-w\right\|^2=\left\|v-w_0\right\|^2+\left\|w_0-w\right\|^2\ge\left\|v-w_0\right\|^2$$
since $\;w_0-w\in W\;$ and we've finished.
Choose now an orthonormal basis $\;\{w_1,...,w_k\}\;$ of $\;W\;$, so for any $\;1\le j\le k\;$ :
$$\left\langle\,v-P_W(v),w_j\,\right\rangle=\langle v,w_j\rangle-\langle P_W(v),w_j\rangle=\langle v,w_j\rangle-\sum_{i=1}^k\langle v,w_i\rangle\langle w_i,w_j\rangle=$$
$$=\langle v,w_j\rangle-\langle v,w_j\rangle=0$$
so $\;v-P_W(v)\perp W\;$ .

Distance and uniqueness for projections


Trouble with inheritance

Question: I'm relatively new to programming so excuse me if I get some terms wrong (I've learned the concepts, I just haven't actually used most of them).
Trouble: I currently have a class I'll call Bob its parent class is Cody, Cody has method call Foo(). I want Bob to have the Foo() method as well, except with a few extra lines of code. I've attempted to do Foo() : base(), however that doesn't seem to work like. Is there some simple solution to this?
Answer: You can override Foo in the derived class and call the overridden base class implementation using base.Foo():
class Cody
{
    public virtual void Foo()
    {
        Console.WriteLine("Cody says: Hello World!");
    }
}

class Bob : Cody
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Bob says: Hello World!");
        base.Foo();
    }
}

Output of new Bob().Foo():

Cody says: Hello World!
Bob says: Hello World!
Cody says: Hello World!

Constructors use a slightly different syntax to call the constructor in a base class, because they have the requirement that the base class constructor must be called before the constructor in the derived class:
class Cody
{
    public Cody()
    {
    }
}

class Bob : Cody
{
    public Bob() : base()
    {
    }
}

Answer: The standard form (without polymorphism) is:
class Cody
{
    public void Foo ()
    {
    }
}

class Bob : Cody
{
    public new void Foo()
    {
        base.Foo(); // Cody.Foo()
        // extra stuff
    }
}

If you want polymorphism, the following 2 lines change:
// Cody
 public virtual void Foo ()

// Bob
public override void Foo()

The difference shows when calling on a Bob instance through a Cody reference:
Bob b = new Bob();
Cody c = b;

b.Foo();    // always Bob.Foo()
c.Foo();    // when virtual, Bob.Foo(), else Cody.Foo()

Comment: The unfortunate side effect of this is that if you have a list of "Cody", put in a Bob, iterate through and call "Foo" on the list, it will still call the Cody method, not the Bob method.
Comment: @Tom, I was still editing. But you don't _always_ want or need polymorphism. It is a choice.
Answer: You need to mark the base method as virtual, override it in the inherited class, and then call the base that way.  You can either call the base before or after your code in the "Cody" class it is up to you on calling order.
class Bob
{
  public virtual void Foo()
  {

  }
}

class Cody
{
  public override void Foo()
  {
    base.Foo()
    // your code
  }
}

Comment: They may have Visual Studio open already and bang out these with AutoCompletion =)
Comment: i guess, or they only post half the answer, then come back and make it pretty later.
Comment: Thanks guys, I really appreciate the help and examples. =) and yeah Intellisense on here would be awesome.

Trouble with inheritance


First Propaganda mision will not complete

Question: I have destroyed everything in the propaganda center and it will not register as complete. It does not gives me any further instruction either. I've done the mission 3 times but it just won't give me credit for it.
Any ideas on how to finish this mission?
Answer: Just like everything else in the game, fry cry highlights everything that's objective related.
There is a red meter on the top of your screen that shows your progress. Go through each room and take out all computers, stamping machines, boxes of posters, Transportation vehicles, and most importantly the power generator.
Power generators needs to be taken out using C4 or explosives of some kind. After all this is finished, you'll get a few more waves of men, take them out. And that should complete the mission.
Comment: You can take out the generator with an LMG as well.
Answer: You have to destroy all propaganda material and kill all enemies surrounding the area. Maybe if you do mission like I did - use the Buzzer and grenade launcher to destroy the propaganda and kill all targets - it will work.
Answer: Sometimes the pick-up trucks fail to count as 'destroyed' even when they've been blown up. If they're still 'flashing' and a handful of C4 doesn't change this, then you sadly have to restart the mission.
Answer: Have you blown up the big blue electricity box at the top of the hill that overlooks the area? It is behind the building with the printing machines in it and up the hill
Answer: I had the same thing happen to me.
Try blowing up the tower on top of the hill if you haven't already.


Result from pipelined function, always will sorted as "written", or not?

Question: Needed get renumbered result set, for example:
  CREATE OR REPLACE TYPE nums_list IS TABLE OF NUMBER;

  CREATE OR REPLACE FUNCTION generate_series(from_n INTEGER, to_n INTEGER, cycle_max INTEGER)
  RETURN nums_list PIPELINED AS
      cycle_iteration INTEGER := from_n;
  BEGIN
      FOR i IN from_n..to_n LOOP
          PIPE ROW( cycle_iteration );
          cycle_iteration := cycle_iteration + 1;
          IF cycle_iteration > cycle_max THEN
             cycle_iteration := from_n;
          END IF;
        END LOOP;
        RETURN;
  END;

  SELECT * FROM TABLE(generate_series(1,10,3));

Question is: there is guarantee, that oracle always will return result in that order? :
1
2
3
1
2
3
1
2
3
1
or maybe sometimes result will unexpected ordered, like this:
1
1
1
1
2
2
....

?
Comment: The data you will see is random sort, unless you add "order by"
Answer:
Pipelining negates the need to build huge collections by piping rows
  out of the function as they are created, saving memory and allowing
  subsequent processing to start before all the rows are generated

pipelined-table-functions
This means, it will start processing the rows before get fetched completely and that's why you are seeing unpredictable order.


wsimport -clientjar generates classes in (default package)

Question: I'm using the -clientjar wsimport parameter to export my WebService into a jar.
>wsimport -d C:\webservice -keep -clientjar webservice.jar http://localhost:8080/WebService?wsdl

A folder with the source code (.java files) and a webservice.jar are created.
The jar looks like this:
com
  |
  company
        |
        webservice
                 |
                 a bunch of .class files

META-INF
       |
       wsdl
          |
          wsdl file

However, when I put it on the WEB-INF/lib folder in my project, the classes are in the (default package) and are named like
com\company\webservice\file.class

I can't understand why. I've also used the -p parameter to specify a package name but it doesn't work.
Any clues?
Comment: same here. any clues?
Comment: when I use the `-clientjar` option the jar generated as a result of that contains **only** a META-INF folder.
Answer: I think the problem here is that -clientjar option is meant for an entirely different purpose than the OP expects.
The purpose of the -clientjar option is to embed a copy of the WSDL inside the generated artifacts so that it can become part of the application's jar file.  The benefit of having a bundled WSDL (and actually using it of course) is that the web service consumer does not have to make a call to the endpoint to download the WSDL every time it initiates itself.
Links:
https://weblogs.java.net/blog/ramapulavarthi/archive/2010/09/03/wsimport-clientjar-option-ease-client-side-web-service-progra
Using jaxws-maven-plugin with -clientjar option
Comment: The problem with this is that I found I need to modify the code generated by wsimport because it does not generate a working SOAP call without a small modification.  If I modify the source and recompile with Eclipse, it wipes out the met-inf folder with the wsdl file in it.
 I have not yet found why wsimport.exe doesn't generate working code from the wsdl file that the website publishes.  I need to add an annotated "action" parameter to the IELDSubmissionService.submit() method with header attribute set to "true", and it then works.  But I have not found an elegant way to build this.
Comment: @sb4. Maybe post your question as a new question on SO ?
Answer: There are two options of achieving this , both works like a charm.
And both options can be automated from ant\gradle you name it .
1.To use -clientjar and then to repack the sources
2.Manually insert the wsdl into jar and customize the wsdLlocation URL
Assuming you have C:\WSDL\SO\stas.wsdl
(I was running on windows)
CD  C:\WSDL\SO\

First option
C:\WSDL\SO>wsimport -clientjar StasWebServiceClient.jar stas.wsdl

This creates  StasWebServiceClient.jar jar file , but when importing it to eclipse, the sources are not importable , because of the topic problem (default package).
=> Unzip the jar file to current folder  , you can use 7zip, or any other great zip tool , or you can run
C:\WSDL\SO>jar xf StasWebServiceClient.jar

to unzip the jar .
Folder hierarchy should look like
C:\WSDL\SO\META-INF

C:\WSDL\SO\stas.wsdl(original wsdl)

C:\WSDL\SO\StasWebServiceClient.jar(generated jar file)

C:\WSDL\SO\META-INF\wsdl(created by -clientjar)

C:\WSDL\SO\META-INF\wsdl\stas.wsdl(copied by -clientjar)

C:\WSDL\SO\com\...

/* all generated classes\sources */

C:\WSDL\SO\com\...

=> Do
C:\WSDL\SO>jar -cvf StasWebServiceClientCorrect.jar com META-INF

this will create another jar , StasWebServiceClientCorrect.jar , which now has the correct packaging .
Second option
=> Run wsimport
C:\WSDL\SO>wsimport -keep stas.wsdl

to generate the code .I always like to have -keep option there , but it's up to you.
=> create META-INF folder
C:\WSDL\SO>mkdir META-INF

=> Create META-INF/wsdl folder
C:\WSDL\SO>cd META-INF

C:\WSDL\SO\META-INF>mkdir wsdl

=> go one folder up .
C:\WSDL\SO\META-INF>cd ..

=> Copy stas.wsdl file into META-INF\wsdl\stas.wsdl
C:\WSDL\SO>copy stas.wsdl META-INF\wsdl\stas.wsdl

=> Create a jar archive
C:\WSDL\SO>jar -cvf StasWebServiceClient.jar com META-INF

Import the jar to workspace.
When you will be creating the actual call to the service , use :
StasService stasService = new  StasService(StasService.class.getClassLoader().getResource("META-INF/wsdl/stas.wsdl") )

Answer: I had the same problem. Finally decided not to use the -clientjar option and generated a jar manually with jar.exe and works.
Answer: 1.) Unzip/unjar clientjar
2.) jar file using
jar cvf <jarName>.jar <root_folders>

example:
jar cvf weather.jar com META_INF

Answer: I used -clientjar so it will do all the work for me, but used my favorite file archiver to unzjar and jar it again.


Problem with Maven execution after installation

Question: when i run mvn -v i get the below error:

bash: /usr/local/apache-maven/apache-maven-3.3.1/bin/mvn: No such file or directory

At /usr/local/ there was a apache-maven directory and i deleted it. And i deleted the symlink pointed to the mvn in bin directory of apache-maven-3.3.1.
I have extracted apache-maven-3.3.3 directory at /usr/local/.
I have edited the /etc/environment file to include the Maven related environment variables and PATH. Here is my environment file.
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/apache-maven-3.3.3/bin"
JAVA_HOME="/usr/lib/jvm/java-8-oracle"
M2_HOME="/usr/local/apache-maven-3.3.3"
M2="/usr/local/apache-maven-3.3.3/bin"
MAVEN_OPTS="-Xms256m -Xmx512m"

So i have clearly included in the PATH, /usr/local/apache-maven-3.3.3/bin where mvn executable exists.
which mvn returned this

/usr/local/apache-maven-3.3.3/bin/mvn

What am i missing..? I'm a novice for Linux environment.
Answer: I found the issue.
type mvn
mvn is aliased to `/usr/local/apache-maven/apache-maven-3.3.1/bin/mvn'

that means there has been a alias created for mvn. this was further assured by
$alias
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
alias mvn='/usr/local/apache-maven/apache-maven-3.3.1/bin/mvn'

I removed the alias by
unalias mvn

Now it works!


Close currentsession in Facebook login in xcode?

Question: I m integrating Facebook login in my app.
I have a Log out button in my app.When user clicks Sign Out then Facebook's current session should be closed .Again if I click Login it should show Login screen of Facebook.
When Log out button is clicked:
<code>appDelegate.fbEmail=nil;
 if (FBSession.activeSession.isOpen) {
        [appDelegate closeSession];
    }

AppDelegate.m

-(void)closeSession
{
     [[FBSession activeSession] close];

}
-(BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI{

    NSArray *permissions=[[NSArray alloc]initWithObjects:@"email", nil];
    return[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
        [self sessionStateChanged:session state:state error:error];
    }];
}
</code>
After he clicks logout it changes to login.Now when login is clicked Login screen of facebook should appear..How to do it ?
Answer: Could you try FBSessionDelegate Methods? Inside FBSessionDelegate have methods to handle session. In this case, i think you can use this function to handle you question :
<code>- (void)fbDidlogout
{
    // your code to get login screen here!
}
</code>
This function will called when the request logout has succeeded. Hope this will help, Cheers
Comment: But I dont have idea how to call login screen bcoz at the application launch it starts from -(BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI{.Can u please tell me how.?When Logout is clicked it will  change the button text to login.Now when Login is clicked it should redirect to login screen of facebook.