Sticker peeled off paint from wall

Question: I removed some kid stickers on the wall and it peeled off the paint.  Hoping to fix this myself but not sure on the best route to take. Attaching a picture of the damage, what are the exact steps I should follow here?
Based on initial research, I think the steps are:
(1) get spackle and spread over area with putty knife and wait for it to dry
(2) sand with 100? grit
(3) apply layer of paint (given it's just a few spots, is it ok to skip the primer?)
Any detailed guidance would be appreciated, first time at this.  Thank you!
Comment: Hello, and welcome to Home Improvement. I'm guessing you should use 220 or finer sandpaper, but beyond that I don't know.
Comment: perhaps the first thing to do, is to wash the wall
Answer: It looks to me like that is just the top layer of paint. Assuming that is the case - i.e., the drywall underneath is not damaged beyond small scratches - you don't need to use any spackle. In fact, doing so would be a lot of work because you don't have any real holes to fill - you'd be sanding nearly all of it off.
However, you can't just paint over the existing paint. You need to sand it down so that you don't have real edges from the old paint. Primer wouldn't hurt. If you are going to repaint the same (or very similar) color & finish then you may be able to get away with primer just over the damaged & sanded areas, but that might result in an inconsistent topcoat.
The most important thing though is that you should repaint the whole wall. Otherwise, even with a near-match on the color, the difference between old & new will be quite obvious. If you use a close-enough color, you can get away with painting just one wall and not the rest of the room.
Comment: Thanks. What grit do you recommend to use for this particular job?  And to confirm I understood this correctly, I just need to use primer only on the damaged area right?  And if I have the same color, then topcoat only on damaged area is fine otherwise repaint entire wall.
Comment: What grit sandpaper? No clue. I paint rarely enough that I honestly just don't know. Yes, primer on damaged area will probably be OK. But topcoat really should be the whole wall. Even with a near-match, it will just look different between fresh paint and last year's (or older) paint.

Sticker peeled off paint from wall


org.apache.felix.framework.cache.BundleArchive: Unable to create archive directory

Question: googling I gound that this error is shown when windows can't run a .bat
I'm getting this when I'm running roo comand in my workspace.
OS -> windows 7, 32 bits
jdk -> jdk1.6.0_22
roo -> spring-roo-1.1.0.RELEASE
The hole error message is:
ERROR: Unable to create system bundle directory.
ERROR: org.apache.felix.framework.cache.BundleArchive: Unable to create archive directory.

Repeated hundreds of times.
I followed all these steps, but anyway I'm getting the error. Does anybody know why??
I read another similar problem, which was solved moving from OpenJDK to JDK 1.6. But I have already JDK 1.6
Thanks in advance
Answer: I also have same issue today on windows 7, 64 bit. after spending some time solved it.

Goto %ROO_HOME%/bin ( for me ROO_HOME = C:\Program Files\springsource\spring-roo-1.1.5.RELEASE)
Right Click Roo.bat and select option 'Run As administrator' from pop-up.
----------------------------------OR-----------------------------
In Run box ( last option in Start button pop-up), type cmd
Instead of hitting Enter, use CTRL + SHIFT + ENTER. Click yes on pop-up box
Command prompt with Administrative Properties will come up, type ROO and it comes up.
( C:\Windows\System32\cmd.exe)
Answer: I had the same problem. I did not have the aprropiate rights to the installation folder of roo. Then I changed my rights and everything worked fine.
Answer: It's probably because you are running as a 'normal' user yet the internal Felix OSGI container, by default, tries to create a felix-cache directory in the working directory.
Two solutions which are probably better than simply elevating your permissions:

Set the org.osgi.framework.storage system property (e.g. -Dorg.osgi.framework.storage=C:\Users\MyUsername)
Run it from a different working directory, one that you have write permissions for


Way to check status of tomcat apps through command line NOT via Tomcat Manager

Question: I am trying to create a way to automatically check the status of tomcat manager via script and email if there any issues at a certain time. I've searched online and I couldn't find any satisfactory answer on how to do this other than this.
And like one commenter suggested in that page, this does sound tremendously stupid that isn't a way to do this other than going via wget and fetching it like that. I refuse to believe it!
Question is, does anyone know of an easier way?
Comment: It is not stupid at all. You should not check tomcat. It is better to check the application that is running inside tomcat. And this can be done for example with a specific health check page that is polled, for example by using wget
Answer: It seems the easiest way I found to do this is the with the following tool:
https://github.com/kotfu/tomcat-manager


Integral acceleration expression

Question: I have a small question! Where does the +20 and -40 come in the picture below. Here are the full expressions of the acceleration. a1=5t,a2=-5t+20, a3=5*t-40
In the picture there is max accelation of 10 and ares T1 = 2  and T2 = 6 and T=8
Teachers tip was to calculate with areas of the triangles, but i cant get the same answers.

Please ask if you need more information and i will try to explain.
Comment: I don't understand your question.  You are given the picture first and you are asked to try to figure out what equations represent the picture?  For that, to see the $+20$ or the $-40$, imagine that those lines extended all the way to the $y$-axis.  Where do they intersect with the $y$-axis?  Well, the line for $A2$ would intersect the $y$-axis at the point $(0,20)$.  That is where the $20$ comes from.
Comment: If instead, you are given the equations first... then the answer to the question of where the $20$ and the $-40$ come from would be "*from the author's imagination*"
Answer: The $+20$ comes from the fact that the function $a_2$ equals $10$ at $x=2$ and has a slope of $-5$. Putting this in the linear equation formula we get the $y$-intercept. Same thing for $a_3$
Comment: @StudentFromFinland Let $a_2=-5x+b$, then we know that $10=-10+b$. Solve for $b$. Now let $a_3=5x+c$, we know that $-10=6*5+c=30+c$. Solve for $c$
Comment: Okey. Just how exacly does it mean its +20 because it equals 10 at x = 2 ? and how does it translate to a3 ? when at x=6 its -10

Integral acceleration expression


Delete app from Play Store that was disabled

Question: I got the following problem:
I published an app that had to do with Corona. I didn't know that Google doesn't allow this (unless it's approved by your government in some way), so Google disabled the app directly.
I have tried to just delete it then, so it doesn't appear in the Dashboard anymore, but I couldn't find how to do this. I've searched the internet on how to delete disabled apps and it seems like that is not possible.
Now that would be fine, but there's the following issue:
Since it was disabled, Google Admob says "one of my apps violates the terms of use of Admob". There also isn't a direct problem with that, but Admob just sent me an E-Mail yesterday that says

Google will introduce a new strike-based system to enforce against advertisers who repeatedly violate Google Ads policies

So I need to remove the App. How can I do that?!

Here's a screenshot that shows that everything is greyed out and therefore I cannot delete the app the normal way:
Comment: I didn't downvote your question, but I think it's because you just have to search the internet for a simple (How do I remove this app ..?) And it tells you that you can't do it, explaining that at most you can cancel the publication on the Play Store, or hide it also on AdMob, but you cannot delete an app published on the Play Store or linked on AdMob.
Comment: My advice is: unpublish on PlayStore and contact AdMob (I don't know if you will be able, but with a disabling problem I think so) explaining what happened.

As for the email I received it too as I think everyone. It does not have to do with disabling the account but is simply a message sent to tell you that the policies will change, as they do so many times.
Comment: I don't see a way to cancel something in the Play Store. And I cannot delete it on Admob because I have several apps published that use the same App-ID in Admob. And as said, I have searched the internet and what I've found is indeed that it seems impossible to do. But first, the answers are some years ago and things change. Especially things change when Google introduces a new strike system. So I don't see why this question isn't valid. I think it's very important.
Comment: Here you can find how to remove the app from the publication: https://stackoverflow.com/questions/34846872/how-to-unpublish-an-app-in-google-play-developer-console
As for downvotes, maybe next time you say that you know it can't be done from what you've been looking for but you're asking if things have changed.
Because otherwise it may seem that you are just someone who does not want to search, which it seems you are not.
Comment: Thank you for the link, but that doesn't work because as said, everything is greyed out. I cannot click on "Advanced Settings" nor on anything else. I have edited and added a screenshot
Comment: Ah well yes rightly having removed them it would be useless for you to do it too.
Have you tried to contact support?
I ask you because if it is as you said I think the appeal will fail.
Answer: You can't do it unfortunately. The only thing you can do is fix the problem and only then delete it.
Comment: Okay, but how can I fix the problem? I'm not allowed to change the app name or the APK, it's all greyed out. The only thing I can do is submit an appeal that I think they made a mistake.
Comment: Only google can fix. You can explain your reasons!
Answer: You can do it by select app and then setup option > Advance setting  here you can unpublish and more setting with you app
Comment: Sorry, can you please elaborate? Which options should I click?
Comment: At Google play console > From application dashboard click on "Setup" and then Advance setting and Unpublish


How can one add the dotcover exclude file settings to the TFS?

Question: I'm trying to add the "exclude file" settings (for jetbrains-dotcover) that I make to the TFS in order to
avoid co programmers having to set the same settings manually.
After trying around and searching I didn't find any info there and thus my question is:
Is this possible to do? And if so how?
Comment: How are you running doTCover in TFS?  You will need to describe what you are doing in greater detail in order to get a decent answer.
Comment: I'm not running it "on" the TFS. I'm storing the projects (aka the whole solution) in TFS. I'm running dotcover "normally" by right clicking on the Unit tests project and click "cover unit tests with DotCover". Then I have to include new files in the DAL project from the dotcover (dal isnt part of those tests). When I then check in into the TFS my co workers need to also exclude those projects or files themselves manually instead of having the same exclude settings as me there. And that is what we want to avoid: Everyone needing to do the same.   That what you meant there @a.vector ?
Comment: Yes that makes more sense.  I've expanded my answer.
Answer: I am presuming that you are running dotCover from the command line in TFS.  With reference to the documentation on running DotCover from the command line you need to add a parameter to your call to exclude the assemblies:
/Filters=ARG                 : (Optional) Specify coverage filters using following syntax: +:module=;class=;function=;
                                 Use -:myassembly to exclude an assembly from code coverage. Asterisk wildcard () is supported here
If you have a dotCover xml file for your coverage settings you can put the exclusion into it.  See the same documentation for editing the xml.  I imagine the bit you need to add would look something like this:
<Filters>
  <ExcludeFilters>
    <FilterEntry>
      <ModuleMask>AssemblyToExclude.dll</ModuleMask>
      <ModuleMask>*Tests*</ModuleMask>
    </FilterEntry>
  </ExcludeFilters>
</Filters>

There is some general info in the documentation on how to set up running from the command line.
*Proviso: I haven't tried what I have suggested, I am merely projecting from my own DotCover/TeamCIty TFS experience.  More information may provide a more accurate answer.
Update:
If you are using dotCover as per @Thomas comment, then you can edit the filters for you machine by running dotCover and selecting File=>Edit Coverage Filters...  If you add a filter there it will also apply to any coverage run from Visual Studio.  For example adding an assembly *Test* exclude filter will stop any assembly with the word Test in from being included in the reports:

I would think that your team would need to have the same exclusion filters setup on all their machines.
Update2:
I found where the per solution filter settings are stored.  They are in your DotSettings file next to your sln (e.g. MyProject.sln has MyProject.sln.DotSettings).  In order to get the exclusion into this file you should in Visual studio with your solution open go to DotCover->Edit Coverage Filters and Add a Filter for the current solution.

This yields the following info in your DotSettings file:
<s:String x:Key="/Default/FilterSettingsManager/CoverageFilterXml/@EntryValue"><data><IncludeFilters /><ExcludeFilters><Filter ModuleMask="*Maths*" ModuleVersionMask="*" ClassMask="*" FunctionMask="*" IsEnabled="True" /></ExcludeFilters></data></s:String>

If you commit the DotSettings file to TFS your team will get the exclusions.  See the docs about sharing your settings here and the docs and about setting them up here.
Comment: hmmm we are using it by clicking on the appropriate command to start dotcover so we aer not using the command line option there.
I didnt see the .xml in the TFS does one have to manually include it for this to ave a chance to work? (thus that you can "deoploy" your exclude settings and not have them solely locally)?
Comment: @Thomas, I've updated the answer (again ;) ) to show how you can do this.


Excel conditional formatting: directional arrows based on the value (like hand of a clock)

Question: Is it possible to use Conditional Formatting for the following purpose:
I need to display a directional arrows based on the value.
Ex.: 0 (arrow points to top); 180 (arrow point to bottom), 90 (arrow points to right), -90 (arrow points left). If the value is 15, arrow must reflect that change.
I am to have all kind of values from -180 to + 180.
Comment: How many arrow you want to have there, 4 or more? and what happens for values between the arrows, like if there is an arrow for 0 and one for 90 what should be the direction of 30?
Comment: is VBA-based solution acceptable? and: How many "arrows" is there likely to be in total?
Comment: Hi, sorry for the late response. I'd lke to have 18 positions, every 20 degrees.
Comment: Any solution is acceptable, thanks!
Comment: Gents, 12 positions are fine (every 30 deg)
Answer: Well this is hard without VBA coding. I have done similar thing but using 8 different arrows (because I can find only 8 arrows from the Symbols menu). Here is how I did it. If someone knows how to add own icon sets with more arrows, this could be done easily using Condtional Formatting -feature in Excel.
To some cell, insert your sumbols found from Insert-ribbon:

So the content of a cell looks like shown below. You create a formula (shown in D1) that calculates which character to get from A1:

=ROUND(C1/45;0)+4

(45 is a number 360 divided by 8)

Then yo draw an arrow:

=RIGHT(LEFT($A$1;ABS(D1+1));1)

And you get the result something like this


KDE 5.21 update is not available on apt in Ubuntu 20.04

Question: I was using Ubuntu 20.04 and then I install and switched to KDE Plasma desktop. Now I'm using KDE 5.18.5 and I want to upgrade to the latest version (5.21), but there's no update on apt.
My question is: How can I upgrade KDE Plasma to 5.21?

Also I've added kubuntu ppa and its backport but no update after running sudo apt update and sudo apt upgrade
~  sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Comment: Does this answer your question? [Why don't the Ubuntu repositories have the latest versions of software?](https://askubuntu.com/questions/151283/why-dont-the-ubuntu-repositories-have-the-latest-versions-of-software), also see https://launchpad.net/~kubuntu-ppa/+archive/ubuntu/backports/+packages?field.name_filter=&field.status_filter=published&field.series_filter=focal
Comment: Plasma 5.21 is not available in that PPA, and cannot be installed this way. In case you want to use Plasma 5.21, you can upgrade to Ubuntu 21.04 (to be released in April 2021) instead. Alternatively, you can use [KDE Neon](https://neon.kde.org/), which is based on Ubuntu 20.04, but the KDE packages are updated to their latest version. Note that KDE Neon is not an official flavour of Ubuntu, and it is not  supported in this site. See the link posted by N0rbert to see why Ubuntu does not always update to the latest version of software.
Comment: What is the question?
Comment: @N0rbert I've added more detail and my question. Specifically, How can I upgrade KDE Plasma to 5.21?
Comment: @David I added more detail and question.
Answer: Upgrade from this PPA: https://launchpad.net/~savoury1/+archive/ubuntu/kde-5-80 - Backport of KDE 5.80 stack (and dependencies) for Xenial, Bionic & Focal.
Comment: Is it safe? Have you tested that it does not break anything?
Comment: Not yet, going to. I tried 2 other PPAs of this author: `ffmpeg4` and `multimedia` - nothing broken, looks like very professional work.


Air Conditioning Thermostat Wiring

Question: A set of three air-conditioners cool a storage building in an American sub-tropical environment.  There is no heat: AC only.  Cooling is signaled by switching the RED (24V) to:

Yellow wire (cooling relay) AND
Green wire (Fan relay)

When cooling is engaged the same 24V from the red wire is connected to both the Yellow (cooling relay) and Green wire (Fan relay).
For a given AC unit, is there any reason to not short the yellow wire to the green wire?  This would simplify the controller design and reduce wiring for a set of three air conditioners.
Comment: I take it you're OK with not having the ability to ever turn the fan on by itself?
Comment: @ThreePhaseEel  Yes.  Is there any reason to run the fan without cooling?
Comment: I could see where this'd be done under mild conditions (I have to do it in my own house under part-load to get anywhere close to comfortable)
Answer: Measure the voltage between the yellow and green wires, if it is zero volts  there's no reason not to connect them.  It most-probably is zero volts.
Comment: I added additional commentary to the OP to reflect that YEL and GRN are shorted together through RED when the fan and cooling relays are engaged

Air Conditioning Thermostat Wiring


jquery step and send var data in php page

Question: I use the jquery script step form
http://www.jquery-steps.com/Examples
The form is divided into fourstep and the final step I finish a button that opens a alert window but I would like to send the variable post or get to a php page
I replaced it
onFinished: function (event, currentIndex)
                {
                    alert("Submitted!");
                }

I replaced the alert by window.location
onFinished: function (event, currentIndex)
                    {
                        window.location.href = "test_insert.php";
                    }

but  do not transmit any data to my php page
thank for your help
Comment: This is because you are simply redirecting user to page "test_insert.php" and not posting any data on this page..
Comment: thank goodface87 and Vishal.
 how I transmit variables ?  i have input like ``  and i know I should do this  `code`$.ajax({
   type: "POST",
   url: "some.php",
   data: **"name=John&location=Boston"**,
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });`
what should I put in the place of **"name=John&location=Boston"**
Answer: I suggest you use jQuery's ajax function instead of trying to navigate the whole window to your php page.
onFinished: function (event, currentIndex)
{
  $.ajax({
    type: "POST",
    url: "test_insert.php",
    data: { yourParameterName: yourVariable }
  })
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
}

In the data part, you would just have to send whatever your php expects.
Comment: thank for you answer , i found this solution in the doc of ..Form Wizard using jQuery Steps... `onFinished: function (event, currentIndex)
{
    var form = $(this);

    form.submit();
}` the form data ar sent to my php page.


processes and multiple jvm

Question: This may be a trivial question and I just want to confirm my understanding on processes and multiple jvms.
I created a C++ dll program calling my java jar file via JNI. I then call this C++ dll in other C++ programs. As far as I know, in any particular program that I call the dll, only one jvm is allowed. In my project, a C++ program calls the dll once at the beginning and the end of the program, and the dll would create jvm when dll is called the first time and attach a thread to jvm when it called the second time.
My question is I will have many different C++ programs calling this dll, so it should create multiple jvms? This is one jvm creation per process, right? Or they are still considered as threads?
Thank you!
Answer: A C/C++ program calling into Java APIs will create one JVM per process (when you call JNI_CreateJavaVM()) and connect to it.
If you have several instances (processes) of this C/C++ program running, then in that case there is one JVM created for each of those instances.
Each JVM created is a process, not a thread.

processes and multiple jvm


Sort Options in a Select List with javascript/jQuery.. but not alphabetically

Question: I am looking for a function that will take a list of options in a select list and sort them alphabetically but with a twist. All values with the text 'NA' should be pushed to the bottom of the list.
So given a list -
<select>
    <option value="1">Car</option>
    <option value="2">Bus</option>
    <option value="3">NA</option>
    <option value="4">Bike</option>
    <option value="5">Tractor</option>
    <option value="6">NA</option>
</select>

We should end up with -
<select>
    <option value="4">Bike</option>
    <option value="2">Bus</option>
    <option value="1">Car</option>
    <option value="5">Tractor</option>
    <option value="3">NA</option>
    <option value="6">NA</option>
</select>

The order of the NAs is not important.
And don't ask why I cannot just remove the NAs (or why there will be several options with the same texts but different underlying values, because I don't agree with it either.
Comment: Worth noting for all these answers: sorting will change which option is selected. You must persist the value of the select element before the sort and restore it afterwards.
Answer: demo: http://jsfiddle.net/4bvVz/
function NASort(a, b) {
    if (a.innerHTML == 'NA') {
        return 1;
    }
    else if (b.innerHTML == 'NA') {
        return -1;
    }
    return (a.innerHTML > b.innerHTML) ? 1 : -1;
};

$('select option').sort(NASort).appendTo('select');

Answer: var sb = $('select');

sb.append(sb.find('option').sort(function(a, b){
    return (
        a = $(a).text(),
        b = $(b).text(),
        a == 'NA' ? 1 : b == 'NA' ? -1 : 0|a > b
    );
}));

Answer: If you have more than one select in the page (multiple selects) use this:
function NASort(a, b) {
    if (a.innerHTML == 'NA') {
        return 1;
    }
    else if (b.innerHTML == 'NA') {
        return -1;
    }
    return (a.innerHTML > b.innerHTML) ? 1 : -1;
};

$('select').each(function( index ) {
    $(this).find('option').sort(NASort).appendTo($(this));
});

Answer: I've made some changes to the original function and it worked fine.
function NASort(a, b) {
    console.log(a.innerHTML.substr(0, 1).toLowerCase() + ' > ' + b.innerHTML.substr(0, 1).toLowerCase());
    return (a.innerHTML.substr(0, 1).toLowerCase() > b.innerHTML.substr(0, 1).toLowerCase()) ? 1 : -1;
};

$('select option').sort(NASort).appendTo('select');


How do I create a list of multiple columns of a file depending on row index?

Question: I'm not a programmer and use python for analyzing electrical grid over powerfactory.
I have a result of a simulation, to deal with there is a bunch of functions which belong to PowerFactory. This result contains  around 3000 columns X 3000 rows. I need to extract a definite columns to deal with.( I can't do that from powerfactory before simulation)
For Ex. my result:
Bus0     Bus1     Bus2    ....   Bus3000
0        0        0              0
1        1        1              1
2        2        2              2
..       ..       ..             ..
3000     3000     3000           3000

How to create a list, which contains only for ex.;
Bus0        Bus2
0           0
1           1
2           2
..          ..
3000        3000

Thank you
Comment: What format is the data in? Is it plain text as shown in your post or is it something else? If plain text, then the csvreader module should be able to parse this
Comment: I'm afraid this is too broad for the Stack overflow Q&A format,  suggest you look into the `pandas` library for dealing with this sort of data. e.g. https://datascienceparichay.com/article/read-csv-files-using-pandas-with-examples
Answer: Actually it depends on a bunch of orders which concern with both of PowerFactory and Python.

Export a class of objects from result of a simulation (For Ex. AllBB)

To create a list of definite Busbars, the codes of these elements have to be known which probably depend on sorting of the elements in Project.

import numpy
BB_List = numpy.array([AllBB[0], AllBB[2]])

To deal only with this list, for ex. to read the max. and min voltages on these busbars over a period of time (day, month or a year)

for BB in (BB_List):
    Voltage = Result.FindColumn(BB,'m:u1)
    Max_Voltage = Result.FindMaxInColumn(Voltage)
    Min_Voltage = result.FindMinInColumn(Voltage)


how to supply a timezone flag to bazel test?

Question: As bazel test encyclopedia said, UTC is bazel time zone. I am wondering is there any way that I can let bazel use system zone i.e Local?
Answer: You can use --action_env to pass in environment values, e.g.,
bazel test --test_output=all --action_env=TZ=Local :tz_test
INFO: From Testing //:tz_test:
==================== Test output for //:tz_test:
timezone: Local
================================================================================
Target //:tz_test up-to-date:
  bazel-bin/tz_test
INFO: Elapsed time: 1.034s, Critical Path: 0.05s
//:tz_test                                                               PASSED in 0.0s

Note that this won't "un-cache" the test result, so you have to run bazel clean first to get bazel to pick up the environment variable change.  I filed a bug about that.
Answer: If the test is a java_test, you can use the user.timezone JVM flag as an attribute on your java_test rule. E.g.,
java_test(
    name = "Test",
    test_class = "TZTest",
    srcs = [
        "TZTest.java",
    ],
    jvm_flags = [
        "-Duser.timezone=EST",
    ],
)

You can confirm that this works with TimeZone.getDefault().getDisplayName().


How find the length of an array

Question: Story:
In fact this question is related to THIS.
How to create an array maintaining following conditions-
1.Total - 10
2.Won   -  7
3.Lost  -  3
4.Longest Winning Streak - 5
5.Longest Losing Streak - 2

Now I need to generate an array of random boolean values (true representing a win and false representing a loss) which fulfills the above criteria.
So, in this case the output can be any of the following:
0011011111
1111101100
1010011111
..........

Question:
I created a script that showed me that under above conditions array length will 112 see at best.
How to know what will be the length of this array when Total,Won and Lost value is changed- better a general rule based on the chnaging values of all the 5 values/conditions mentioned above.
Comment: For the particular case:Let's call the longest winning streak W and longest losing streak L. Then W is a sequence 11111 and L is 00 that leaves us with 2 more 1's and a single 0. Now arrange the set $\{W,L, 1, 1, 0\}$ in such way that W is surrounded by zeros.
Comment: @user26977  then how will you get 112 for the above conditions?
Comment: Can we interpret the win/loses as sum of kind of a game that is we are playing 10 distinct games in which $5$ consecutive results should be a win ...etc..etc...and all that is there in the question...
Comment: @Freelancer Nops not any condition out of the mentioned above.
Answer: For the particular case:Let's call the longest winning streak W and longest losing streak L. Then W is a sequence 11111 and L is 00 that leaves us with 2 more 1's and a single 0. Now arrange the set $\{W,L,1,1,0\}$ in such way that W is surrounded by zeros.
You have 2 possibilities $LW0$ and $0WL$. For the remaining 1's you have 3 possibilities (put both in front, put both in the end, or 1 in front and 1 in the end). This gives you total of 6 possibilities.
The general case can be treated similarly, take the winning streak, put loses around etc, but the number of branches will grow quickly. You can start with $L$ if it is longer then $W$ as well.

How find the length of an array


Permanent feed from light swicth

Question: Here is my question, I want to pull power (Live and Neutral) from a 220 Volts light switch. But my house is wired up like in FIGURE 1: (all images referenced below are in 1 image marked as Figure 1, 2, 3 and 4)

Now what I have noticed is that when the light switch is not switched on, I get a power between point A and point B (FIGURE 2) (excuse my horrible drawing :-))
But now when I switch the light switch on, power between point A and point B comes and goes (AC- Alternating Current). All of this I understand and it makes logical sense. Now lets say I have a 220V to 5V charger connected between point A and point B (FIGURE 2), the charger would just switch ON and OFF at what ever hertz the power is running at (50-60 HZ). If I had to place a 400V 100uF capacitor (FIGURE 4) between point A and point B, would that give just enough power to power the charger for that (working on 50 HZ) 20 milliseconds or am I having the wrong idea here. Or might there be another way to do this? Because I bought a Touch Light Switch from LEAR (looks about the same as FIGURE 3) and they are able to work on the way that my lights are connected/wired. Now I have seen 1 or 2 of these exact questions around but people just ask who do they do it. My question is if I place the Capacitor there (FIGURE 4), would it help? If anyone could please assist me with a solution for this or even let me know if i am working in the right direction. Thank you so much.
Comment: What you are describing makes no sense.  When the switch is on your points A & B are shorted and the light goes on.  When the switch is off, there is power between points A & B only because your lamp completes the circuit.  You cannot power another appliance from points A & B as the voltage will split between the lamp and the appliance and neither will work properly.  The capacitor you show is intended only for DC operation and is complete unsuitable (and unsafe) to use on a 220V AC circuit.
Comment: Please clearly say what you are trying to achieve without clouding your statements with possible solutions, Say what you want then you can rant about this or that afterwards.
Answer: If you want to tap off power from that switch, you'll need to tap from "point B" and "N". Then you'll get continuous power, regardless of the light switch's on/off position.
If you connect that electrolytic capacitor in any manner to that light switch circuit, you'll understand with no doubts exactly why you should not do that - your room will instantly be decorated with tinsel and electrolyte from inside the capacitor - electrolytics are really hostile to being connected to municipal power lines.
Answer: You cannot get power at the switch that is suitable for tapping in to feed off to some other location.
In similar manner, with your current wiring, you cannot deploy a smart type switch that requires a separate neutral connection.
To get power into the switch box in a legitimate manner you will have to string a new wire between the light fixture box and the switch box that contains a black, white, red and GND wire. The black and white will bring power to the switch box and the red would be used to return switched power to the light. Here is a doctored up version of the picture that you linked.
Finally as others have said, please drop the idea of that capacitor. It would explode if you tried attaching it to the power lines.

Comment: Hi Michael - I stumbled upon your diagram from google images. I have a similar problem, but in reverse. Would this diagram work if the power source is the at the switch box, and but a constantly-powered circuit continues instead from the light box?

Thanks

Permanent feed from light swicth


what to use in place of NULL in QUEUE made by LINKEDLIST

Question: i came to know that due to AMBIGUITY that can be cause by poll function we are not recommended to use NULL value in a QUEUE made by LINKEDLIST.Then what should be inserted in place of null?
Answer: Have you ever heard about Null Object Pattern? This should help you, i think.
Comment: If you can't or don't want to put object with null value to your linked list. Prepare an object which is called NullObject (NullObject class - NullQueueObject / NullQueueElement for example). That object must have specified value that could be easly recognized in your algorithm (some value instead of null in your case) - that object could be skipped, deleted, replaced etc.
Comment: You could define individual behaviour (methods) for that object. If you want more details, check these links [wiki](https://en.wikipedia.org/wiki/Null_object_pattern), [pattern explained](https://sourcemaking.com/design_patterns/null_object). Tell me if it works for your case.
Answer: I got the answer..
What we can do is to create a Linked list node containing a particular value(for example Integer.MAX_VAL) and use that node as a representation of null type.


typing/mypy: difference between dict[key] and dict.get(key)?

Question: Here's my test script:
class A:
    def __init__(self, config: dict) -> None:
        self.config = config

def test_func(a: int) -> None:
    pass

main_config = {"a": "x"}
a = A(config=main_config)

# value direct
test_func(1)  # line 14
test_func("b")  # line 15

# value with wrong type from dict
test_func(main_config["a"])  # line 18
test_func(main_config.get("a"))  # line 19

# value with wrong type from dict in class instance
test_func(a.config["a"])  # line 22
test_func(a.config.get("a"))  # line 23

If I test it with mypy (0.910) then I get the following result:
> mypy test.py
test.py:15: error: Argument 1 to "test_func" has incompatible type "str"; expected "int"
tests.py:18: error: Argument 1 to "test_func" has incompatible type "str"; expected "int"
tests.py:19: error: Argument 1 to "test_func" has incompatible type "Optional[str]"; expected "int"
tests.py:23: error: Argument 1 to "test_func" has incompatible type "Optional[Any]"; expected "int"
Found 4 errors in 1 file (checked 1 source file)

Why does mypy miss/not report the call on line 22?
Comment: Does this answer your question? [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey)
Comment: @adirabargil It's a question about mypy interpretation of them, not their functionality.
Comment: ok i cancled it
Answer: Just an assumption:
dict.__getitem__() (a.k.a a.config[...]) does not have type annotation. While dict.get has:
def get(self, key: _KT) -> Optional[_VT_co]: ...

Simple proof of my assumption:
from typing import Optional, Any

def test_func(a: int) -> None:
    pass

def foo(a):
    if a == 1:
        return 123
    elif a == 2:
        return 'asd'
    else:
        raise ValueError

def foo_typed(a) -> Optional[Any]:
    if a == 1:
        return 123
    elif a == 2:
        return 'asd'
    else:
        return None

test_func(foo(2))
test_func(foo_typed(2)) # line 26

Produces only:
main.py:26: error: Argument 1 to "test_func" has incompatible type "Optional[Any]"; expected "int"

Even though foo(2) returns string.
Comment: But both 18 and 19 raise errors; 22 is different only because the object being indexed is an instance attribute, rather than an object whose value is known statically.
Comment: Hmm you are right. I guess that's the limitation of mypy. It looks at `config: dict` and doesn't know the type of `config[...]` at all (as it is not defined in type anotations of `dict.__getattr__`). And it sees that `dict.get` has type annotation `-> Optional[Any]`.
Comment: Even `mypy --strict` doesn't seem to care about the mismatch. Either it's a bug in `mypy`, or there's some subtlety to how unannotated functions are handled that I don't understand. (I was assuming that `test_func`'s need for an `int` would override the lack of a defined return value for `__getitem__`.)
Comment: The same lack of an error occurs with `test_func(foo())` where `foo` is unannotated, so I don't think my initial thought about `a.config` being an instance attribute is relevant.


When bolting down a porcelain toilet, how tight is "too tight"?

Question: Tightening bolts on the base of a toilet is the one thing about toilet installation that has me the most nervous.  They say not to over-tighten, but how tight is too tight before the porcelain is subject to cracking?  Do I tighten until I can't tighten anymore?  Do I tighten it just before I think it's at its tightest?
Comment: If the porcelain cracked, it was too tight!
Comment: Last one I installed used the guideline of "tighten fully by hand, then use the wrench to give it one quarter turn more." Check what your unit's manufacturer suggests.
Comment: While many of the answers boil down to "so it won't leak" I am mostly concerned that  small bowl movements will pull the bowl away from the seal.
Answer: I start by hand tightening as much as I can, then I tighten a little on each side and check if the toilet moves.  If it does then I tighten a bit more, check and repeat until there's no movement.  You're trying to avoid bowl movement, so that it doesn't shift or fall over, not to hold the floor up by the toilet bolts.
As tight as you can go will probably snap the porcelain (with a good socket you can torque a nut onto a bolt quite a bit).  Until you think it's about to snap is just guessing.
Snug.  No movement.  Enjoy.
"Too tight" is a sixteenth of a turn past where the porcelain snaps :-)
Comment: I almost sprayed coffee on my screen when I read "_You're trying to avoid **bowl** movement_". :)
Comment: The length of your wrench will affect the "feel" of tightness. I have a ratchet with a 2" handle (the most expensive wrench in my toolbox) that I use whenever I don't want to over-tighten a nut (and don't have an explicit torque setting).
Comment: Exactly - the point of the bolts is to hold the toilet in place, NOT to create the seal.  The seal is created by the wax ring.  One quarter turn too far on that bolt and you've ruined a multi hundred dollar toilet.  If it doesn't move when you sit on it, it's *tight enough!*
Comment: Good answer.  I basically tightened the nuts to the point where the toilet was level and did not move at all.  One last question, though: When I lay my level across the bowl and apply upward pressure on either side of the bowl, the level indicates that there is very slight movement because the bubble moves a tad to the left and right (still within level parameters).  However, I can't feel the movement myself.  Does this seem fine?
Comment: @oscilatingcretin I would personally be ok with it, since the normal operating conditions will have pressure in the downward position, but then I'm more paranoid of over tightening than falling off.
Comment: It should be fine to check to see if the toilet moves when it is almost fully tightened. This will help the toilet become fully seated in position. This small level of movement will not deform the wax ring to the point where it will leak. A toilet can be moved quite a bit before the ring fails. You definitely want to make sure that it is completely secure, and tightened down evenly. As long as the pressure is even, you can make it quite tight without breaking the bowl. The trick is to stop when the nuts stop turning with a reasonable amount of force.
Comment: Do **not** move the toilet to see if it's snug. By doing this, you will deform the wax and it probably won't seal well. Never rock the toilet as it is sitting on the seal!
Comment: @user13872 Ok, then how *do* you check for proper snugness?
Answer: One thing that will help prevent the porcelain cracking is to use a rubber or plastic washer between the head of the bolt and the bowl.
This will take some of the "excess" force by deforming slightly, and by checking for the washer deforming as you tighten you'll have an extra visual check that you've applied enough force.
Comment: Yeap, not only will it take excess force, it will provide good hold of the toilet so that it doesn't swing.
Answer: Best practice is to hand tighten nuts, sit on toilet to assist with setting wax ring, tighten nuts to a point of being snug and alternate tightening nuts, then sit back on toilet and if toilet moves, tighten slightly. Check if toilet is level, shim to level, and flush toilet. If leaks, repeat process of sitting on toilet and slightly tighten nuts in an alternating fashion.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: My grandfather was a master plumber for more than 50 years.  I asked him one time how tight to make a sink faucet shutoff valve connection. His answer is a classic ... "Tight enough so it don't leak".  There is a lot of wisdom in this.  The answer for the toilet is the same thing, not too tight but tight enough.
Answer: The toilet can wiggle for two reasons: bolts not tight or floor not even (hello old houses!).  After tightening the bolts a little bit and making sure you really set that toilet on the ring, see if you need to shim one or two gaps.  In my case, i too was worried about cranking down hard on the bolts.  The shims stabilized the toilet nic
Answer: When you put the toilet in place, with the wax sealing ring between the toilet flange on the floor and the toilet itself, the toilet will be held off the floor a bit by the wax ring. Sit on the toilet backwards (facing the tank - so you can see and reach the nuts) to squish the ring in place sealing the toilet to the flange on the floor. Tighten the nuts on the closet bolts (that attach to the flange) such that the toilet is flat on the floor without rocking.
Tighten it down a bit on one side then the other, then do it again. Rinse and repeat, until the toilet is flat on the floor. If you tighten it too much, you can pull the closet bolt out through the flange, ruining the flange or breaking the porcelain.
DO NOT tighten it as tight as it will go, like you're building something or working on your car - you'll break the flange, chip or crack the porcelain or both.
Most toilets are made of vitreous china. Vitreous china is a glass based enamel coating / glazing technique that is added to porcelain to make it more durable, denser, and shinier. It is also what fine dinner ware, plates, dishes and cups are made of.
Answer: Whatever length wrench you're using, choke up on the handle all the way.
"Too tight" begins once you start deforming the washer.
Once you do start to deform the washer, you have to toss the, "hand tighten, then 1/4 turn with a wrench," out the window (not that I've ever found that sentiment to be satisfactory). I've never cracked a toilet by over tightening its bolts. The washers that come with a bolt kit are intentionally flimsy.
If there's a word for the day, it's : snug (for which you either need years of experience, or one cracked toilet, to know when to say when).
My preferred finishing touch is, once it's sung, grout it in place (keeps hair from getting stuck in the grove, and other yuckiness) and then I guarantee, it will not rock. My preferred tool, is my little six inch adjustable wrench. I don't choke up on it, but I know when to say when.
Answer: You should never grout or silicone your toilet in place. If for some reason you have a leak at the connection between the flange and wax ring it will collect under the bowl and by the time you notice it, it will may have ruined the floor under it not to mention the condensation that is being created in that pocket which you created by sealing it. Also, the mess you will have to clean up when you eventually replace that toilet. I would much rather remove hair and "yuckiness" then grout or silicone with more "yuckiness" attached to the silicone or grout and or run the risk of damaging the floor to remove it... as far as tightening goes, hand tighten, go one full turn with perfered tool, sit on the bowl, slightly lift your left leg and right leg to see if the toilet rocks if it does turn bolts a half turn, rinse repeat till no Rocking occurs, assuming you have a fresh nice flange. 534 Water closets installed. $


I am getting error on defining a portion of html code in a variable in JavaScript file

Question: I am getting the error as defined below for a piece of code in html written in a JavaScript file ->   This is the error
D:\OnlineBookStore\RouteHandler.js:23
                 var  html= "
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Invalid or unexpected token
←[90m    at wrapSafe (internal/modules/cjs/loader.js:1001:16)←[39m
←[90m    at Module._compile (internal/modules/cjs/loader.js:1049:27)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:950:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:790:12)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:974:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:93:18)←[39m
    at Object.<anonymous> (D:\OnlineBookStore\BookRouting.js:1:20)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1085:14)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)←[39m

For the var html part in the below file it is giving error -> This is the part of code
exports.display_signup=function(url, request, response){
         response.writeHead(200, {'Content-Type': 'text/html'});
         var  html= "

Book Cart

SignUp

                   <form name='myform' action='http://localhost:3000/register' method='post'>

                             UserName:
                             <input type='text' name='username' value=' ' />

                             Password:
                             <input type='password' name='password' value=' ' />

                              Confirm Password:
                              <input type='password' name='confirmpassword' value=' ' />

                              Address:
                              <input type='text' name='address' value=' ' />

           <input type='submit'  value='Register' />

                   </form>

         ";

response.write(html);
Comment: Include all errors and relevant code in the body of your question ***as text***, not as images - it takes fewer clicks to copy/paste your code than it does to screenshot and upload your code. It also allows potential answerers to better assist you because we won't have to re-type every single line of code to reproduce your issue. [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question)
Comment: Looks like you have a line break in your string. That's not allowed.
Comment: that  is not a tag it is just defining the background color of the body tag
Comment: Duplicate of https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript
Answer: So the query is resolved i used  `` symbol instead of "".
this resolved my issue.


A column that's omitted during split-apply-combie in pandas

Question: I'm doing a split-apply-combine to find a total quantity for each member. The dataframe I need should have 14 columns: MemberID, DSFS_0_1,  DSFS_1_2, DSFS_2_3, DSFS_3_4, DSFS_4_5, DSFS_5_6, DSFS_6_7, DSFS_7_8, DSFS_8_9, DSFS_9_10, DSFS_10_11, DSFS_11_12, DrugCount. However, I'm not getting the 14th one (DrugCount), any idea why? The variable joined outputs all 14, but joined_grouped_add, the function in which I do aggregation, only returns 13.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
from sklearn.cross_validation import train_test_split
from sklearn import linear_model

# this function takes the drugcount dataframe as input and output a tuple of 3 data frames: DrugCount_Y1,DrugCount_Y2,DrugCount_Y3
def process_DrugCount(drugcount):
    dc = pd.read_csv("DrugCount.csv")
    sub_map = {'1' : 1, '2':2, '3':3, '4':4, '5':5, '6':6, '7+' : 7}
    dc['DrugCount'] = dc.DrugCount.map(sub_map)
    dc['DrugCount'] = dc.DrugCount.astype(int)
    dc_grouped = dc.groupby(dc.Year, as_index=False)
    DrugCount_Y1 = dc_grouped.get_group('Y1')
    DrugCount_Y2 = dc_grouped.get_group('Y2')
    DrugCount_Y3 = dc_grouped.get_group('Y3')
    DrugCount_Y1.drop('Year', axis=1, inplace=True)
    DrugCount_Y2.drop('Year', axis=1, inplace=True)
    DrugCount_Y3.drop('Year', axis=1, inplace=True)
    return (DrugCount_Y1,DrugCount_Y2,DrugCount_Y3)

# this function converts strings such as "1- 2 month" to "1_2"
def replaceMonth(string):
    replace_map = {'0- 1 month' : "0_1", "1- 2 months": "1_2", "2- 3 months": "2_3", "3- 4 months": '3_4', "4- 5 months": "4_5", "5- 6 months": "5_6", "6- 7 months": "6_7", \
                   "7- 8 months" : "7_8", "8- 9 months": "8_9", "9-10 months": "9_10", "10-11 months": "10_11", "11-12 months": "11_12"}
    a_new_string = string.map(replace_map)
    return a_new_string

# this function processes a yearly drug count data
def process_yearly_DrugCount(aframe):
    processed_frame = None
    aframe.drop("Year", axis = 1, inplace = True)
    reformed = aframe[['DSFS']].apply(replaceMonth)
    gd = pd.get_dummies(reformed)
    joined =  pd.concat([aframe, gd], axis = 1)
    joined.drop("DSFS", axis = 1, inplace = True)
    joined_grouped = joined.groupby("MemberID", as_index = False)
    joined_grouped_agg = joined_grouped.agg(np.sum)
    print joined_grouped_agg
    return processed_frame
def main():
    pd.options.mode.chained_assignment = None
    daysinhospital = pd.read_csv('DaysInHospital_Y2.csv')
    drugcount = pd.read_csv('DrugCount.csv')
    process_DrugCount(drugcount)
    process_yearly_DrugCount(drugcount)
    replaceMonth(drugcount['DSFS'])

if __name__ == '__main__':
    main()

Comment: And where are the lines that call the function(s)?
Comment: Too, too much is going on here to help. I advise breaking each part and adding print statements to view content to see where column is removed. Otherwise, set up a [reproducible example](http://stackoverflow.com/help/mcve).
Comment: I did print outputs along the way and broke it up. That's how I know that everything is fine, until I do the aggregation `joined_grouped_agg`
Answer: Simply put, DrugCount pulled directly from csv is not reading in as a numeric field (int/float). Otherwise it would be retained in the .agg(np.sum) processing. Before aggregation check the dtype and see if it is an object type (i.e., string columns):
print joined['DrugCount'].dtype

In fact, in your process_DrugCount() function, you explicitly convert DrugCount column into integer with astype but do not do so in process_yearly_DrugCount() function. Run same line in latter function and DrugCount should be retained in aggregate sum processing:
aframe['DrugCount'] = aframe['DrugCount'].astype(int)

Or better yet, in main() to avoid doing conversion twice in latter functions:
drugcount['DrugCount'] = drugcount['DrugCount'].astype(int)

Also, do note, read_csv() allows explicit designation of columns types with its dtype argument:
drugcount = pd.read_csv('DrugCount.csv', dtype={'DrugCount': np.int64})


Washing Machine Stator Wire Harness Melted

Question: I have a Kenmore 40318900 front loader that started giving the LE error(motor stall). I bought it as a display model 5 years ago. Tub spins freely by hand, I started troubleshooting according to the tech manual I found inside(quite convenient) and it said the stator was bad due to resistance being way out of spec. I took the stator out and to be 100% sure measured windings directly, and lo and behold they were all fine, around 8 ohms each. Then I figured it was in the harness and sure enough one of the wires had 1.2k ohms between the stator pin and the pwb connector. I started following the wire harness and found a melted and burnt section.
While going through the machine I also noticed one of the three shock absorber is missing the mount pin. Looked all over the laundry room and turned the machine on it's side and it is nowhere to be found, no broken pieces. My thought is it must've never been installed. The washer has always been pretty noisy and vibrates around on the tile floor.  My hypothesis is that the excess vibration may have frayed the strands in the wire and caused it to overheat due to the current flowing through a lot less copper. The fix should be a simple wire replacement, but I wanted opinions before I power it up and risk a fire. Any thoughts?
Edit: I ended up cutting about 4 inches out of the blue and yellow wires and splicing/heat shrinking some new wire with butt connectors. I also found out a 1/2" bolt fits where the shock mount pin was missing and put one and a nylon lock nut in. Ran one load of laundry and all seems well, but will monitor it for a bit for heat.
UPDATE: It's been a month and the washing machine has been fine. Seems it was simply the wire chafing. Thanks all
Comment: This is what is called CHAFING. Your assumption the constant vibration and movement of the washer rubbed off the insulation (chafing) is probably very valid - however you can minimize that in the future by securing the wiring to a stabilized surface and limit the movement or rubbing of the wires against any other surfaces. Use additional wire ties and tie downs - that will save you in the long run.
Answer: Wire flexing over time breaks the strands , this is not uncommon in equipment that moves. I would consider replacing the section that was flexing unless there was a single loop but even then do not shorten the over all length because a shorter area for flexing will cause higher stress on the wires. If anything a longer splice will reduce stress as it allows more area for flex.
Comment: I can't accept both answers but believe this one is still valid. Thanks!
Answer: From the limited I see, I tend to agree.  For some reason it looks like you have had an extremely high resistance point in the wire.  (It could have been due to abrasion) I would sign off on a good quality patch job.  Cut the wire back far enough to get to good clean non-damaged non-overheated conductor.  Make sure you fix the yellow at the same time. If you machine is doing a lot of walking, make sure you fix that too.  Something is wrong.


How to restrain duplicate links from getting parsed?

Question: I've written some script in python to scrape the next page links available in that webpage which is running well at this moment. The only issue with this scraper is it can't shake off duplicate links. Hope somebody will help me accomplish this. I've tried with:
import requests
from lxml import html

page_link = "https://yts.ag/browse-movies"

def nextpage_links(main_link):
    response = requests.get(main_link).text
    tree = html.fromstring(response)
    for item in tree.cssselect('ul.tsc_pagination a'):
        if "page" in item.attrib["href"]:
            print(item.attrib["href"])

nextpage_links(page_link)

This is the partial image of what I'm getting:
Comment: You make a set, add all links processed and check if the link is already in there before processing.
Answer: You can use set for the purpose:
import requests
from lxml import html

page_link = "https://yts.ag/browse-movies"

def nextpage_links(main_link):
    links = set()
    response = requests.get(main_link).text
    tree = html.fromstring(response)
    for item in tree.cssselect('ul.tsc_pagination a'):
        if "page" in item.attrib["href"]:
            links.add(item.attrib["href"])

    return links

nextpage_links(page_link)

You can also use scrapy which will by default restrict duplicates.
Comment: Thanks Sumit Gupta, for your answer. It works. You should take out the print statement from your script. Btw, scrapy handles duplicates if item pipeline is properly handled.
Comment: Thanks, removed the `print` statement :)


Passing int to and returning class from dialog

Question: New to java and swing so please explain fully in your answers.
I have a class with 5 ints in it.
on my jframe i have a button, when you click it it should open a dialog with 5 comboboxes and an ok button.
I want to pass an int to the dialog to tell it how many itmens to put in the first combo box, the other 4 have fixed values.
on pressing the ok the dialog shoudl get the values form the comboboxes and fill out a class instance and return that instance.
i have read a lot of tutorials, i understand i need a custom class but dont know how to make it in netbeans, new class just gives me a code editon and no design view.
I dont know how to call the custom class dialog or to pass it a varialble.
please dont link me here iv read it at least a hundred times.
EDIT: what iv tried.
I tried making a cunton Dialog in netbeans but its built it into the main frame. I tried making it in a class but i dont know how to call the class and im sure the class code is wrong anyway.
Comment: If you have read the docs: What have you done already?
Answer: The show__Dialog methods of JOptionPane accept Object for the "message". This can be anything: namely a custom JPanel that you have created.
Create a JPanel, put your comboboxes in it, show it in a JOptionPane, then retrieve what you need.
Here is an extremely short example:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        JPanel    panel = new JPanel();
        JCheckBox check = new JCheckBox("Yes or no?");
        panel.add(check);

        JOptionPane.showMessageDialog(null, panel);
        JOptionPane.showMessageDialog(null,
            "You entered " + (check.isSelected() ? "yes" : "no") + "."
        );
    }
});

(The JCheckBox could have also been passed to showMessageDialog directly.)
The JOptionPane doc is fairly specific about how message is handled. Look under "Parameters: message". According to the doc, you could even pass it a JComboBox[].
Comment: does it have to be all in one source ? can i make the jpanel a seperate .java ?
Comment: Yes, you can extend JPanel. Or make a factory method. As long as `message` is a subtype of `java.awt.Component`, JOptionPane will know what to do with it.
Answer: One way to do this would be a custom Dialog with a method that accepts your int and has a return value of the class you want to get back.
Now you create a new Instance of this dialog in the calling class. This should set up the Dialog as far as possible but not switch it visible yet.
Now as the triggering method is called you switch the combo boxes to the right settings,set the dialog visible,wait for the Ok button to be pressed, assemble the return object and send it back.
Comment: I dont think you understand, i have 8 years C++ expierience and about 20 minutes of java, I want to do excatly what you say, its perfect i just have abssoultley no clue at all how to do it. i dont know how to create an instance in the callign class, or how to give the dialog a return type
Comment: creating a new instance would be something like 'MyDialog dlg = new MyDialog();' and further down 'MyReturnClass ret = dlg.getUserInput(intToCompleteSetup);' to get the values you want
Comment: I might have misinterpreted what you meant: you should extend a *JFrame* for this.
Comment: You really should not extend JFrame to use it as a dialog box. (For a custom dialog box from scratch, extend JOptionPane or JDialog.) http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice


How do I resolve this Google API dependency issue?

Question:
I'm unable to enable the Google Calendar API. I've followed all the instructions present in the Google developer website to the letter. I've tried all the ways possible. I've downloaded all the necessary SDK tools and extra resources but this issue still persists. Please help!
I've installed Android support repository, Google play services, Google repository. This problem is still there.
Comment: Did u check this http://stackoverflow.com/questions/34805574/android-studio-import-google-api-failed
Comment: @Raghavendra Yes, I've done that, it still isn't working!
Comment: could you show your full gradle file?
Comment: post it then. let's see if we could have something to make right there!
Answer: go to setting (or press Ctrl+Alt+S) and find gradle part then disable  the Offline work . after that connect your PC to net and try to sync the gradle.
or you can remove all dependencies from gradle file (build.gradle) and try to add them again . you can see this link  :
Android Studio with Google Play Services
at the end If that not work . you have to download all libs that you added in compile section and
add them to your project.
Comment: I've disabled it. It's still not working. Thanks for your input, though!


CakePHP 3.0 - Using MySQL functions in Entities

Question: I'm having trouble with using MySQL functions with CakePHP database entities. The few mentions I have found in my searches have only been for previous versions of CakePHP, and no longer work.
Also, using PHP's functions to generate a date is not an option. It must be done on the MySQL server.
Here is an example of my code:
$record = [
    $this->_table->primarykey() => $id,
    "a" => $a,
    "b" => $b,
    "c" => $c,
    "updated_on" => "NOW()"
];
$result = $this->_table->save(new Entity($record));

This is resulting in a default datetime value of 0000-00-00 00:00:00 in the updated_on field in the row in my database, instead of populating it with the current timestamp.
Bonus Points: If I wanted to add a created_on field, how would I handle that with Entities? How could I set created_on only once when the record is first inserted, rather than on every update?
As always, I very much appreciate every comment and answer!
Comment: it would be better if you make `updated_on` field in your db as `date` or `time` or `datetime`
Comment: Just for my understanding, you want to update the `update_on` whenever an entity has been altered and you want to set the `created_on` when it's created? Take a look at: http://book.cakephp.org/3.0/en/orm/behaviors.html#using-behaviors
Comment: @Anant the field in the database is a `datetime`, but I want to set it's value to the result of the MySQL function `NOW()`.
Comment: @Sevvlor That's exactly my question. But I also framed it this way in the hope that I could reuse the answer when I need to use other MySQL functions in an insert/update call using entities.
Comment: *Why?* The function won't do anything different nor is there any dramatic performance impact? Edit: Actually now() can make it slower https://coderwall.com/p/eslwuw/why-not-to-use-now-in-mysql
Answer: Proper Architecture
First, I would not do any business logic operations inside an entity. Especially not placing the code inside the entity. If you really think you must do it there, then call at least just a table method and encapsulate the logic there. An entity is thought to be a data object, nothing more. So doing save operations inside the entity inverts the architecture. This should be done inside the beforeSave() callback of the model.
Why is NOW() vs phps date() required?

Also, using PHP's functions to generate a date is not an option. It must be done on the MySQL server.

Why? I don't see a reason to not do so. Different timezone setting or something? Performance? NOW() is probably slower if you have lots of writes. Well, just make your phps default timezone match whatever the DB is using? You could then simply use the Timestamp behavior. I'm happy to learn something new about the implications of not using NOW() vs using date() but so far I see absolutely no need to use NOW().
Using NOW() with the CakePHP 3 ORM
If you would have read the manual you would have probably seen this:

CakePHP's ORM offers abstraction for some commonly used SQL functions. Using the abstraction allows the ORM to select the platform specific implementation of the function you want. For example, concat is implemented differently in MySQL, PostgreSQL and SQL Server. Using the abstraction allows your code to be portable:

The documentation features an example as well:
// Results in SELECT COUNT(*) count FROM ...
$query = $articles->find();
$query->select(['count' => $query->func()->count('*')]);

Followed by a list of out of the box supported functions that includes:

now() Take either 'time' or 'date' as an argument allowing you to get either the current time, or current date.

If you keep on reading it will tell you

In addition to the above functions, the func() method can be used to create any generic SQL function such as year, date_format, convert, etc. For example:

I haven't had a need to use now() myself yet but based on the above information I guess it would be:
$date = $query->func()->now();

Then just save that value to the DB. I think the unit tests of the framework will show an example of how to use it as well.
Setting the date on create

Bonus Points: If I wanted to add a created_on field, how would I handle that with Entities? How could I set created_on only once when the record is first inserted, rather than on every update?

$entity->isNew() will allow you to check if the entity is new or not and act accordingly. If is new then set timestamp.
Bottom line
You're re-inventing the Timestamp behavior in the architecturally wrong place. It's up to you to do it right or not.
Answer: This probably will not answer your "how can I use MySQL functions" question completely but I can point you in the general direction.
However. To set the created_on and updated_on datetime fields in the table, I would recommend using functions that are provided by Cake. By using the provided Behaviour:
namespace App\Model\Table;

use Cake\ORM\Table;

class ArticlesTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp', [
            'events' => [
                'Model.beforeSave' => [
                    'created_on' => 'new',
                    'updated_on' => 'always'
                ]
            ]
        ]);
    }
}

Adding the Timestamp Behaviour to the table of your entity, you can let Cake's ORM handle the updating of the fields for you.
Comment: Just take a look at the code and see? http://api.cakephp.org/3.2/source-class-Cake.ORM.Behavior.TimestampBehavior.html#126
Comment: Will this use the MySQL server's `now()` function, or the PHP date functions on the webserver?
Comment: Just tested the answer, and looked at the source (thanks burzum), and found it uses PHP date functions.
Answer: The simple answer to this reasonable question is:
use Cake\I18n\Time;

$record = [
   $this->_table->primarykey() => $id,
   "a" => $a,
   "b" => $b,
   "c" => $c,
   "updated_on" => Time::now()
];

$result = $this->_table->save(new Entity($record));

The now() used here will get the time from the PHP server and not the database. But this will be in accordance with the created and modified fields on the same table.


Solve combinatorics tasks

Question: The Question

The student forgot the four-digit identification code of his credit card. What is the probability that a student will receive his money by
typing a code at random if he remembers that:

$\quad$ a) all digits of the code are different;
$\quad$ b) the code does not contain the digits $0$ and $1$?
$\quad$ P.S. a and b are two separated cases

$15$ parcels came to the orphanage. In four of them - winter things, in one - a leather jacket, in the rest - books. Workers open three
parcels randomly. What is the probability that:

$\quad$ a) in two of them - winter clothes and in one - a leather jacket;
$\quad$ b) all three parcels - with books?
$\quad$ P.S. a and b are two separated cases

My Understanding
I tried solving them using formulas and logic
1(a) the total number of possible combinations is $\frac{10!}{ 6!} = 5040$, and the probability $\frac{1}{5040}$?
1(b) there are only $8$ possible digits, repetitions are possible, so the probability is $\frac{1}{4096}$.
2(a)$\frac{2}{455}$
2(b)$\frac{24}{91}$
I've done all calculations using fractions and multiplication because I don't know how to do these using formulas and which
Answer: Your answers are correct except for $2$(a). You do not need to apply much of formula anyway. Some of them did not have the working behind the answer so not sure how you arrived at them.
1(a). As you said each of the four digits are different so there are $10$ choices for the first digit, $9$ for the second, $8$ for the third and $7$ for the fourth digit. That is $10 \cdot 9 \cdot 8 \cdot 7 = 5040$ codes in total and hence the probability that they will enter the right code in one attemtp $ = \frac{1}{5040}$.
1(b). There are $8$ choices for each of the four digits and that is $8^4 = 4096$ codes. So probability $ = \frac{1}{4096}$.
2(a). You seem to have made a mistake in this one. We select $3$ random boxes out of $15$. We need to find probability that one of the boxes has leather jacket and other two have winter clothes. As there is just one box with leather jacket, there is just one way to choose the box with leather jacket. But there are $4 \choose 2$ ways to choose two boxes with winter clothes.
So the probability should be $ \displaystyle \frac{4 \choose 2}{15 \choose 3} = \frac{6}{455}$.
2(b) As we need to find probability that all $3$ boxes have books,
The answer should be $ \displaystyle \frac{10 \choose 3}{15 \choose 3} = \frac{24}{91}$.
Comment: in 2a i was trying to play with fractions 4/15*3/14*1/13 and that's how i got my answer
Comment: But that considers if the third opened box was leather jacket. You need to add probability when the box with leather jacket is first or second as well.
Comment: right, thank you very much

Solve combinatorics tasks


SWIFT: Why isn't my URL to maps app working correctly?

Question: I have code where a user taps an annotation, then clicks a button which gives them directions that the city of said annotation is located in, by sending them to the Maps app. Here's the code:
@IBAction func routingButton(_ sender: UIButton) {

    let annotationAsCLLocation = CLLocation(latitude: coordinatesInTransition.latitude, longitude: coordinatesInTransition.longitude)

     geoCoder.reverseGeocodeLocation(annotationAsCLLocation) { (clPlacemark, error) in
         //print("Reverse geocoding resulted in an error: \(error ?? "" as! Error)")

        // I found the URL strings documentation for opening the route in the Maps app here: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
        if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality)&dirflg=d&t=m") {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
     }
}
// Create function that uses the distanceTo and determines which aspect of the placemark is the closest to the annotation and uses that for the URL
}

Anyway, when I type in the locality of the CLPlacemark that is created (clPLacemark?[0].locality), the URL doesn't send me to the maps app, but when I type in the same locality raw, such as URL(string: "http://maps.apple.com/?daddr=Hague&dirflg=d&t=m") as opposed to the normal way, URL(string: "http://maps.apple.com/?daddr=(clPlacemark?[0].locality)&dirflg=d&t=m"), it works.
In essence, replacing the coded locality accessed through the placemark with the actual name is working, but the coded way isn't.  Any idea why? Thanks.
Answer: You should handle optionals.
Replace:
if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality)&dirflg=d&t=m") {

With:
if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality ?? "")&dirflg=d&t=m") {


How to build a basis for a vector space E(n+1) from a set of points given in E(n) (a vector space of rank n).

Question: I'm interested in how (and if) one can build a new dimension from a set of given dimensions.
Specifically, if we are given a vector space E(n) of rank n, and a sample S of elements of E(n) (let us say, S arbitrarily big):
Can we build a vector basis for some E(n+1) of rank n+1?
I'm also interested in keywords or themes that study this kind of questions in maths (if any).
I've been looking up for Lie brackets, unstable operations in vector fields, and words such as involutivity and extension algebras.
Thank you.
Addendum, following the answers and the questions below: I am working on a data structure where points are taken from $\left\{ 0,1\right\}^{m}$ where m can potentially go to $\infty$. At a given moment, I only have points taken from $\left\{ 0,1\right\}^{n}$ where n < m.
Then, if I want to add an extra dimension, I have m-n possibility to do so - which may be a lot.  Instead of doing this arbitrarily, I would like to have a kind of principled way
or at least a mathematical understanding of such an operation (i.e. that takes as input N points from E(n) and returns a basis for E(n+1).
Thanks again!
Comment: If you want to go up a dimension, you need new elements. Unless your $E(n)$ already lives somewhere larger, you need to do something rather arbitrary to do this (but obviously, you can always formally add a dimension).
Comment: Of course you can always define an $n+1$ dimensional vector space from $n+1$ points, but this potentially won't have anything to do with the old vector space. If a vector space is $n$-dimensional, this is in a hand-wavy sense equivalent to all algebraic operations compatible with the space on all elements yielding at most $n$-dimensional sets.
Comment: Thanks. I assume that E(n) lives on somewhere (much) larger. My aim is to find an operation (or algorithm) that can build B' of E(n+1) out of points in E(n). Or a mathematical notion or result that prove that it can be done (maybe trivially..)
Comment: Where do you assume $E(n)$ to live? It sounds like you have something specific in mind, in which case you need to provide those details.
Comment: It's not clear what you're looking for. What do you mean 'take as input $N$ points from $E(n)$ and returns a basis for $E(n+1)$? If we know what the subspace $E(n)$ is, then we don't need to be given some set of points from it in order to extend it by one dimension. If $E(1)=\{(0,0,\ldots),(1,0,\ldots)\}$ then it's clear that we can extend to $E(2)$ by adding any vector linearly independent from $E(1)$ and the span of $E(1)$ together with this new vector. There's no canonical way to do this, although the simplest would be to consider the new vector $(0,1,0,\ldots)$.
Answer: Let $E(n)$ be a given vector space over the field $K$ and define $E(n+1)$ by $E(n+1)=E(n)\oplus K$ where $K$ is seen as a $1$-dimensional vector space over itself and $\oplus$ is the direct sum of vector spaces. Given that $E(n)$ is an $n$-dimensional vector space over $K$, we see that $E(n+1)$ is an $n+1$-dimensional vector space over $K$ from basic linear algebra.
If $B$ is a basis for $E(n)$ then $B'=\{(v,0_K)\mid v\in B\}\cup\{(0_{E(n)},1_K)\}$ is a basis for $E(n+1)$.
Any other $n+1$-dimensional vector space over $K$ with an embedded $E(n)$ is naturally isomorphic to this vector space via an isomorphism which restricts to the identity on the embedded $E(n)$ subspaces.


Mutable Arc in Rust

Question: Earlier I had a Sync + Send trait SyncMessenger:
trait Messenger {
    fn send_message(&self, user_id: UserId, text: &str);
}

trait SyncMessenger: Messenger + Sync + Send {}

It's implementation:
pub struct DiscordMessenger {
    discord: Arc<Discord>, // (Discord is Sync and Send already)
}
impl Messenger for DiscordMessenger {
    fn send_message(&self, user_id: UserId, text: &str) {
        self.discord.send_message(user_id, text, false);
    }
}
impl SyncMessenger for DiscordMessenger {}

And using it:
struct Bot {
    messenger: Arc<SyncMessenger>,
}
impl Bot {
    pub fn new() -> Bot {
        Bot { messenger: Arc::new(DiscordMessenger::new()) }
    }

    fn messenger(&self) -> Arc<SyncMessenger> {
        self.messenger.clone()
    }
}

struct PingCommand {
    fn fire(&mut self, bot: &mut Bot) {
        bot.messenger().send_message(UserId(0), "Pong");
    }
}

Everything worked fine. Now I want to implement TestMessenger which does not really send a message through a network but toggles a flag in Self instead:
#[cfg(test)]
struct TestMessenger {
    pub message_sent: bool,
}
impl Messenger for TestMessenger {
    fn send_message(&mut self, user_id: UserId, text: &str) { // we have `&mut self` here
        self.message_sent = true;
    }
}

So I need to change send_message(&self) to send_message(&mut self) everywhere (in traits and in implementations). I did that but after I can't compile my user code:
struct PingCommand {
    fn fire(&mut self, bot: &mut Bot) {
        bot.messenger().send_message(UserId(0), "Pong");
    }
}

Gives error:
   |
12 |         let _ = bot.messenger().send_message(UserId(0),
   |                 ^^^^^^^^^^^^^^^ cannot borrow as mutable

error: aborting due to previous error

I have found something that works but it looks very ugly to me (and requires unwrap() which I would like to avoid):
let _ = Arc::get_mut(&mut bot.messenger()).unwrap().send_message(UserId(0),

So the question here is how to do that as much simple as possible, without unwrap()s, static methods like Arc::get_mut? Why simple fn messenger(&self) -> Arc<SyncMessenger> is not possible to call mut methods?
Answer: You can use interior mutability to change data behind immutable references.
use std::cell::Cell;
struct TestMessenger {
    pub message_sent: Cell<bool>,
}
impl Messenger for TestMessenger {
    fn send_message(&self, user_id: UserId, text: &str) {
        self.message_sent.set(true);
    }
}

This struct is for single-threaded cases. You'll need std::sync::Mutex instead of Cell to have Sync for TestMessenger.
Answer: Note that trait methods implemented should be strictly checked for compliance: send_message(&mut self, user_id: UserId, text: &str) is not compliant with send_message(&self, user_id: UserId, text: &str) due to the former's mutable reference to self, and the compiler would eventually complain.
Therefore, interior mutability is required here, so that state changes may happen behind an immutable reference. In this case, since you're dealing with other thread-safe components, you may consider using the thread-safe AtomicBool.
use std::sync::atomic::AtomicBool;

#[cfg(test)]
struct TestMessenger {
    pub message_sent: AtomicBool,
}
impl Messenger for TestMessenger {
    fn send_message(&self, user_id: UserId, text: &str) { // we have `&mut self` here
        self.message_sent.store(true, Ordering::AcqRel);
    }
}

Mutable Arc in Rust


What are the benefits of venturing into the Nether?

Question: My friend is new to Minecraft, and though he has understood the basics of gameplay, he still doesn't understand the point of the nether.
In simple terms, how can I describe the benefits of the nether?
Answer: These are all good answers, but they seem to be tailored to more advanced Minecraft players, and you wanted a KISS answer. (Keep it Simple Stupid)
The Nether is neccesary if your ever wish to craft potions, slay any of the bosses, and\or have access to some other unique things.
The Nether can also be convienently used to travel great (overworld) distances in a short amount of time.
Comment: While @Buhb's answer is tecnincally correct, villagers are random, and the Nether is gauranteed.
Comment: One key point... if you can't buy the Eye of Ender from a villager, then the only way to make it is with blaze powder crafted from blaze rods in the Nether. In short, no Nether == no way to get to The End.
Comment: Also, you won't buy wither skeleton skulls, nether stars or beacons. Mining gold in overworld (even in Mesa biome) will never yield anything close to what a good zombie pigman farm can produce. And your brewing stand won't be of much use without blaze powder to fuel it, and you won't get it from trading either.
Answer: As Per the Minecraft wiki:

The nether can used for traveling traveling large distances on the
above ground map quickly
The nether contains block types not seen anywhere else such as:
Nether Wart (For Potions, can only be grown in the nether)
Netherrack
Soul Sand
Glowstone Blocks (Alternative to Torches)
Nether Brick
Nether Brick Fence
Nether Brick Stairs
Blaze Rods (Used in creating potions and Alchemly lab)
Magma Cream (Used in creating potions)
Ghast Tears (Used in creating potions)

There are five mobs in the Nether can only be found in the Nether:

Ghast
Magma Cube's
Blazes (Only in Nether Fortresses)
Zombie Pigmen (though these can spawn in the overworld when lighting hits a pig)
Wither Skeletons (Also only in Nether Fortresses)

The Nether is also the only place to find Nether Fortresses which contain Nether Bricks and Blaze Spawners. Also the Nether has no night/day cycle and no weather. The only sources of natural light come from the lava, fire, and glowstone located there. Also a compass is useless in the Nether as it will just spin continuously in random directions and the same goes for the night/day cycle clock that can be crafted.
For more detailed information I would recommend reading the whole Minecraft Wiki Nether Page.
Comment: Good stuff, except your parenthetical on Nether Wart is wrong -- it's only *found* in the Nether, but it will grow on Soul Sand no matter where you put it -- I have a Nether Wart farm in the Overworld that's highly productive!
Comment: Ah, well it has been sometime since i last played and when i did it only grew in the nether
Comment: Just a side note Wither Skeletons will rarely drop their skulls which is the key ingredient in having the Wither Boss Spawn
Comment: The entire Nether is permeated with light level 4. It's not just the lava, fire, and glowstone.
Comment: SaintWacko, this comes from the wiki on the nether:  A dim ambient light can be seen throughout the Nether, but this is purely a visual effect and does not affect game mechanics. light works the same way in the Nether as it does in the Overworld: there are 16 levels of brightness and one level falls off for every transparent block it radiates through.
Answer: Apart from the more general fact that there are resources there that you can't get anywhere else, up until recently, you also needed to visit the nether in order to get stuff required for you to reach the ender dragon, considered to be the final boss.
Nowdays you can buy the critical components from villagers, so the trip is no longer strictly required.
Answer: The Nether is the only way to acquire Glowstone, one of the  brightest light sources available along with the Jack O' Lantern, and an ingredient in the creation of the only redstone-toggleable light source. It is also the only way to acquire various brewing ingredients, to wit, Netherwart, Ghast Tears, and Blaze Rods. Netharrack, the material the Nether is built out of, will burn indefinitely, unlike wood. Zombie Pigmen, found only in the Nether, are an unlimited source of Gold Nuggets, which can be combined into Gold Ingots. It is also a near-unlimited source of lava.
Comment: @KBKarma: Not to mention a Blaze Rod is required to build a Brewing Stand
Comment: Since Netherwart is used to make Awkward Potions, and all potions are based on Awkward Potions, the Nether is vital if you ever want to make potions.
Comment: Note that Glowstone Dust (which can be used to craft Glowstone blocks) can be acquired from witches in the Overworld, although it's rare.
Comment: Doubly-vital, then; I'd forgotten about that.
Comment: [Jack 'o' Lantern](http://www.minecraftwiki.net/wiki/Jack_%27o%27_Lantern) and Glowstone both has 15 Lumination
Comment: @Cresh - Oh, that's right! I never use the Jack O' Lantern because it looks odd. Added that to the answer.
Comment: You can find a brewing stand in villages now
Comment: @Shray Yes, but you still need blaze powder to fuel the brewing stand.
Comment: "only redstone-toggleable light source" redstone torches are toggleable light sources


Gaussian Process Regression

Question: I am coding a Gaussian Process regression algorithm. Here is the code:
% Data generating function

fh = @(x)(2*cos(2*pi*x/10).*x);

% range

x = -5:0.01:5;
N = length(x);

% Sampled data points from the generating function

M = 50;
selection = boolean(zeros(N,1));
j = randsample(N, M);

% mark them

selection(j) = 1;
Xa = x(j);

% compute the function and extract mean

f = fh(Xa) - mean(fh(Xa));
sigma2 = 1;

% computing the interpolation using all x's
% It is expected that for points used to build the GP cov. matrix, the
% uncertainty is reduced...

K = squareform(pdist(x'));
K = exp(-(0.5*K.^2)/sigma2);

% upper left corner of K

Kaa = K(selection,selection);

% lower right corner of K

Kbb = K(~selection,~selection);

% upper right corner of K

Kab = K(selection,~selection);

% mean of posterior

m = Kab'*inv(Kaa+0.001*eye(M))*f';

% cov. matrix of posterior

D = Kbb - Kab'*inv(Kaa + 0.001*eye(M))*Kab;

% sampling M functions from from GP

[A,B,C] = svd(Kaa);
F0 = A*sqrt(B)*randn(M,M);
% mean from GP using sampled points

F0m = mean(F0,2);
F0d = std(F0,0,2);

%%
% put together data and estimation

F = zeros(N,1);
S = zeros(N,1);
F(selection) = f' + F0m;
S(selection) = F0d;

% sampling M function from posterior

[A,B,C] = svd(D);
a = A*sqrt(B)*randn(N-M,M);
% mean from posterior GPs

Fm = m + mean(a,2);
Fmd = std(a,0,2);
F(~selection) = Fm;
S(~selection) = Fmd;

%%

figure;
% show what we got...

plot(x, F, ':r', x, F-2*S, ':b', x, F+2*S, ':b'), grid on;
hold on;
% show points we got

plot(Xa, f, 'Ok');
% show the whole curve

plot(x, fh(x)-mean(fh(x)), 'k');
grid on;

I expect to get some nice figure where the uncertainty of unknown data points would be big and around sampled data points small. I got an odd figure and even odder is that the uncertainty around sampled data points is bigger than on the rest. What am I doing wrong?
Answer: There are a few things wrong with your code. Here are the most important points:

The major mistake that makes everything go wrong is the indexing of f. You are defining Xa = x(j), but you should actually do Xa = x(selection), so that the indexing is consistent with the indexing you use on the kernel matrix K.
Subtracting the sample mean f = fh(Xa) - mean(fh(Xa)) does not serve any purpose, and makes the circles in your plot be off from the actual function. (If you choose to subtract something, it should be a fixed number or function, and not depend on the randomly sampled observations.)
You should compute the posterior mean and variance directly from m and D; no need to sample from the posterior and then obtain sample estimates for those.

Here is a modified version of the script with the above points fixed.
%% Init
% Data generating function
fh = @(x)(2*cos(2*pi*x/10).*x);
% range
x = -5:0.01:5;
N = length(x);
% Sampled data points from the generating function
M = 5;
selection = boolean(zeros(N,1));
j = randsample(N, M);
% mark them
selection(j) = 1;
Xa = x(selection);

%% GP computations
% compute the function and extract mean
f = fh(Xa);
sigma2 = 2;
sigma_noise = 0.01;
var_kernel = 10;
% computing the interpolation using all x's
% It is expected that for points used to build the GP cov. matrix, the
% uncertainty is reduced...
K = squareform(pdist(x'));
K = var_kernel*exp(-(0.5*K.^2)/sigma2);
% upper left corner of K
Kaa = K(selection,selection);
% lower right corner of K
Kbb = K(~selection,~selection);
% upper right corner of K
Kab = K(selection,~selection);
% mean of posterior
m = Kab'/(Kaa + sigma_noise*eye(M))*f';
% cov. matrix of posterior
D = Kbb - Kab'/(Kaa + sigma_noise*eye(M))*Kab;

%% Plot
figure;
grid on;
hold on;
% GP estimates
plot(x(~selection), m);
plot(x(~selection), m + 2*sqrt(diag(D)), 'g-');
plot(x(~selection), m - 2*sqrt(diag(D)), 'g-');
% Observations
plot(Xa, f, 'Ok');
% True function
plot(x, fh(x), 'k');

A resulting plot from this with 5 randomly chosen observations, where the true function is shown in black, the posterior mean in blue, and confidence intervals in green.
Comment: 3lectrologos, Thanks for your answer!! I have understood from the literature that the data should be centered before building the GP model, therefore I subtracted mean(f(Xa)) since Xa represent the points and f(Xa) you would get from some measurement. The other comments showed I need to learn more. Thanks again!!
Comment: After second thought, it's OK to subtract the sample mean, but in the end you should add it again to the data points and the GP estimates. (It would only be a problem if you wanted to iteratively add training observations, and estimate the posterior multiple times.)

Gaussian Process Regression


Dell Powerdge840 2.4GHz 64 bit quad core

Question: I am having an issue, where I have changed the boot order to cdrom and turned off hd boot all together and still my system is unable to detect Ubuntu and claims, no boot device found.
Some additional information:
When this same cd is inserted and dell is booted into win 2003 server (which is what is installed on this machine), it detects the cd drive but not the cd at all (keeps asking me to insert disc)
I have also created a bootable flash drive using LinuxLive USB creator and when this is selected in boot order again am told no boot device detected.
I was speaking to dell and they suggested perhaps there are no drivers on the actual Ubuntu installation for the hardware on this Dell and hence the failure of this dell to detect the Ubuntu cd.
Now, I don't know too much about computers, but this last bit confused me a bit. If the system detects the hardware (when it is booting it sees the cd rom and in bios it sees when the flash drive is connected), then shouldn't it be able to read what is on those drives? However, if there is some firmware or software install that needs to happen, could someone please tell me where to find the correct drivers for Ubuntu and dell poweredge to work together?
Shall I be installing the desktop version or the server edition, also, 32 bit or 64 bit?
Answer: From the Dell PowerEdge 840 manuals:
Your system supports the following operating systems:
• Microsoft Windows ServerTM 2003, Standard Edition and Web Edition
• Microsoft Windows Server 2003, Standard Edition 64-Bit
• Red Hat® Enterprise Linux ES (version 3) for Intel x86
• Red Hat Enterprise Linux ES (version 4) for Intel x86
• Red Hat Enterprise Linux ES (version 4) for Intel Extended Memory 64 Technology (Intel EM64T)
• SUSE® Linux Enterprise Server 9 (Service Pack 2 or later) for Intel EM64T
Therefore this is not a Ubuntu-related question - sorry!


Get productType for creating a listing on amazon with SP API

Question: Hello I am developing an integration with Amazon SS API to automate listing products for a specific client.
I have gotten to the point where I am able to generate access tokens.
I can fetch existing listings using get-listings2021-08-01itemsselleridsku endpoint.
I am now trying to create listings using use the put-listings2021-08-01itemsselleridsku endpoint.
I am following this tutorial, but when it describes the JSON object to submit the actual product details to make the listing everything goes super meta.
Apparently you are supposed to use a different api to fetch your product type and then look up the required fields for that specific product type in the schema to know how to represent them.
I have been able to use the product type search endpoint to search for product types, specifically get-definitions2020-09-01producttypes to do searches, but the options which come back are not useful.  You can search by keyword or by product name.  My client sells vinyl records.  So I have searched for music, record, lp, vinyl about anything I can think of and I do not find a valid product type which is returned by that endpoint.
I have searched for this problem and have found an old github issue identifying the same issue, but following the links it circles back to what I already have found.
I am using Postman to make the requests and have imported the relevant models.

How do I find a valid productType for Vinyl Records?
Do different productType's have to be enabled somehow for why the get-definitions endpoint doesn't return useful results?
Is there a different endpoint for creating listings which is recommended which is better supported?
Answer: I had this same problem with books... I was surprised that books doesn't have their own product type. Actually all media including records, do not have their own product type!
I did figure out that a productType of "PRODUCT" will work fro Books and I suspect it will work for records as well.
Here's a sample body for the PUT listing  to help explain what worked for me:
PUT https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/items/{your-seller-id}/{your-custom-sku}?marketplaceIds=ATVPDKIKX0DER
<code>{
      "productType": "PRODUCT",
      "requirements": "LISTING_OFFER_ONLY",
      "attributes": {
        "purchasable_offer": [
          {
            "currency": "USD",
            "our_price": [
              {
                "schedule": [
                  {
                    "value_with_tax": 44.33
                  }
                ]
              }
            ],
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],
        "condition_note": [
          {
            "language_tag": "en_US",
            "value": "Book in good condition. Cover is in good condition. Binding is good. Ships direct from Amazon!",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],
        "fulfillment_availability": [
          {
            "fulfillment_channel_code": "AMAZON_NA",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],
        "batteries_required": [
          {
            "value": "false",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],
        "merchant_suggested_asin": [
          {
            "value": "1718502443",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],`enter code here`
        "condition_type": [
          {
            "value": "used_very_good",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ],
        "supplier_declared_dg_hz_regulation": [
          {
            "value": "unknown",
            "marketplace_id": "ATVPDKIKX0DER"
          },
          {
            "value": "unknown",
            "marketplace_id": "ATVPDKIKX0DER"
          },
          {
            "value": "unknown",
            "marketplace_id": "ATVPDKIKX0DER"
          },
          {
            "value": "unknown",
            "marketplace_id": "ATVPDKIKX0DER"
          },
          {
            "value": "unknown",
            "marketplace_id": "ATVPDKIKX0DER"
          }
        ]
      },
      "offers": [
        {
          "marketplaceId": "1718502443",
          "offerType": "B2C",
          "price": {
            "currency": "USD",
            "currencyCode": "USD",
            "amount": 44.33
          }
        }
      ]
    }
</code>
A few things to note:

requirements == LISTING_OFFER_ONLY  (PRODUCT wont work with 'LISTING')
Everything in the body is required values.
For some reason the price is being set to 0.00 even though I am setting it in multiple places. I haven't figured that one out yet but I'll update when I do)
Last, I am using a known ASIN here so I am not creating a new product. If you are trying to create something not in the catalog then more complications will likely arise!

Hope this helps you out!
Comment: Thank you, that was the trick.  I was able to post.  Now I need to figure out how to specify inventory levels.  My client is not using Amazon's fulfillment services, so I am not sure that the fulfillment_availability applies, but if it doesn't I am not sure what to use.
Comment: Also for me a price was able to get through.
Comment: Glad it helped get you going!  I was able to get the price to go through as well... it was strangely slow to show up in seller central but did eventually get there.  I'm doing FBA only at the moment so haven't dug too deep into the MF side.


Retrieving image url with specific access privileges using AWS Mobile SDK for Android

Question: I would like to retrieve an image URL with non-public access using the AWS Android SDK. I will be displaying the image via the URL myself, but I'm not sure how to go about getting permissions via the secret access key.
I would like to keep these images private, so making them public is not an option for me.
How would I go about doing this?
Answer: There is no way to create a URL to an image with access control built into the URL per se.  Because if the URL alone is what has the access built into it (i.e. it has the signature already embedded), then who has the URL is not relevant.
Assuming you are using Amazon Cognito (which you probably should be) to vend temporary credentials to you application.  You can then use IAM roles to restrict access to this image to just yourself.  From there you could get the image yourself, or using the temporary credentials, create a pre-signed URL.  However anyone with that URL will have access to the image for the duration up to its expiration.
Comment: Keep in mind Dillon, that you can still create a pre-signed URL for an object... but the access control restrictions are on whoever creates the URL, not the URL itself.  So if your account has access, you can create a temporary pre-signed url and pass it around.