How to fix leaking PVC fitting?

Question: I screwed up. I'm usually pretty good with PVC. I used the approved cleaner and primer, and Weld-On 705. I've done this dozens of times.
But here's where I screwed up: one part was a threaded bushing: 1" glue to ½" NPT. I made the mistake of turning in a petcock before the glue cured (nominal 20 minutes).
All the other ~20 glued joints are fine under pressure, but this one bushing is slowly dripping from two or three spots.
I really don't want to re-do the entire assembly, which is what it will take to replace this one bushing.
My spouse suggested a hose clamp. I thought of using a hypodermic needle to squirt some additional 705 around the spot where the bushing meets the "T" fitting. Either of these have merit? Any other ideas?
Comment: You probably have to redo it. Can you cut into a piece near the the leaking fitting to replace it but still keep most of the pieces you have already assembled?
Comment: With two splices and a new "T" and bushing, I can do it. But the leaking has slowed considerably, and it's not a particularly sensitive environment (cement floor), so I'm going to continue to monitor it, rather than throw a bunch of plastic in the landfill.
Answer: The hose clamp is right out.  All you'll do is crack something -- if you're lucky, right away.
Likewise trying to inject PVC cement (705) is not a good idea.  Even if you manage to plug the leaks, the majority of the joint is compromised.   It will eventually fail, and the law practically says it will fail 2 hours after you've left for a 2 week vacation, etc. (^_^)
PVC is super easy to repair or replace, and hacksaws are cheap too.  If it's a particularly difficult section of pipe, consider installing one or two unions, to make the repair easier.
Go ahead and rebuild that section properly.
Comment: My problems are:

1. environmental: I don't want to bring new plastic into the world, and don't want to put more plastic in landfills.

2. cost: I'm living very simply, and I'd rather put the money from even these simple parts into other things.

3. effort: I've got six baby goats and 12,000 seed starts in the greenhouse to care for.

The leak has slowed, and I'm going to monitor it. I don't get off the farm much, and can't remember my last vacation...

(Too bad this site shares Faceplant's hatred of line breaks. I had to copy line breaks and paste them here to format this comment.)
Answer: You'll want self fusing silicone tape.  Dry it.  Wrap it.  Pressure test it.  Done.

How to fix leaking PVC fitting?


Updating problem[Broken package]

Question: I am not able to update software by package manager and also by terminal it show the following message:
<code>Error:Bokencount>0
</code>
Well i tried package manager so it says me to fix broken package first so i went in Package tab and clicked repair broken packages then it started showing zero broken package but now it started showing new error:
<code>**E: /var/cache/apt/archives/burg-theme-lightness_0.5.0-1_all.deb: subprocess new post-removal script returned error exit status 2**
</code>
Answer: Repair broken software package on ubuntu 12.04 and ubuntu 12.10,
To solve broken package problem on Ubuntu, you need to purge it which is related to PPA or software source. There are several way to solve this problem.

Cleaning using two ways command.
sudo apt-get clean && sudo apt-get update
sudo apt-get update
If you fail using the first command, try to use this one:
dpkg --configure -a
Try this command if you failed to remove broken package using the second command:
apt-get install -f

The last command will help you to remove all broken package.

Updating problem[Broken package]


why I get linker errors when trying to set static variable in a class?

Question:
Possible Duplicate:
static member variable in a class
What is an undefined reference/unresolved external symbol error and how do I fix it?

class test_struct {
  static int number;
 public:
  static void set() {
    number = 42;
  }
};

int main() {
  test_struct::set();
}

The error is:
[...]Temp\ccGGxEAz.o:test.cpp:(.text.startup+0xf): undefined reference to `test_struct::number'
collect2.exe: error: ld returned 1 exit status

Comment: http://www.parashift.com/c++-faq/link-errs-static-data-mems.html
Comment: Mentioned in here: http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix
Answer: You need to define static member test_struct::number in a source code(.cpp), before using it:
class test_struct {
  static int number;
 public:
  static void set() {
    number = 42;
  }
};

int test_struct::number = 0;

Comment: in a CPP!  not in the header!


Filter for failed BigQuery jobs in the webinterface

Question: I have a lot of jobs that have run (over 1000) and some of them failed. I can grep for them on the command line with
bq ls -j --max_results=10000 | grep FAILURE and then check each job id with bq show --format=prettyjson -j JOB_ID.
I can filter for jobs in the webinterface, but the filter does not allow me to filter for failed jobs only. At least I cannot see it:

Is it possible to filter for failed jobs in the webinterface?
Comment: Could the people who downvoted this question maybe comment on why they did so?
Answer: I'm with GCP Support. At the moment, it is not possible to filter like that.
As I think this is a good request, I have filled a Feature Request for this in the Public Issue Tracker, where you can follow the updates of this FR.


Azure Data Factory (ADF): Failed to run Pipeline Bad Request

Question: I have a simple master pipeline that executes multiple other pipelines in parallel. When I trigger the individual child pipelines manually, I have no issue. But when I try to run the master pipeline it returns a BadRequest, with an empty message.
<code>"code": "BadRequest",
"message": null,
"target": "pipeline//runid/a15ff459-a32e-4127-8b57-20695d2b1979",
"details": null,
"error": null
}```
</code>
Answer: I figured out that the name of one of the Pipeline execution tasks/blocks has a trailing whitespace, once this was removed the master pipeline was able to run successfully.
Comment: Thank you, thank you, thank you!!! I just tidied up some of my activity names, and you've saved me a whole load of invisible pain...
Answer: I faced the same issue but in my case was related to a missing comma at <code>@concat()</code> dynamic expression.
It wasn't a good troubleshoot since ADF doesn't alert about it at any time.
Regards,
Ogata


Can't connect to specific wifi network

Question: I'm using Ubuntu 12.10 and I can't connect to a specific password-protected wifi network. I have the password and I can connect to it with success in the same laptop with Windows 8.
I can connect to other wifi networks using Ubuntu, so it seems that this specific network is different somehow in a way that Ubuntu fails to connect to it.
When I try to connect it stays in "connecting" state for a long time (2-5 minutes) until it fails with "Connection failed: activation of network connection failed" error.
How can I fix this?
Answer: There are some issues with Intel's implementations of the wireless N standard that doesn't play nice with Linux.  Also sometimes having wired ethernet up can interfere.  I wrote a quick script that I placed into my public GitHub repository that fixes this on most people's systems.  You can find it here: https://github.com/FreedomBen/handy-bash-scripts/blob/master/fixTheInternet.bash
Run that script each time you boot up, and your wireless should work well.  It will be limited to G speeds, but that's still really fast.
If you'd rather run the commands in a terminal yourself, here they are.  The script is handy though because you can just run it everytime you boot and you don't have to remember these commands:
<code>sudo ifconfig eth0 down
sudo modprobe -r iwlwifi
sudo modprobe iwlwifi 11n_disable=1
</code>
Comment: Why eth0? what does that have to do with wifi?
Comment: I tried this on my laptop and the wifi just stopped working at all.
Comment: This worked for me, enabling me to connect to the wifi network. However I was then unable to connect to my iPhone hotspot...
Comment: "Why eth0? what does that have to do with wifi?"

It puts down the wired ethernet that can sometimes interfere.  From the original post:

"Also sometimes having wired ethernet up can interfere."
Answer: Your wifi module drops the connection, the router might have N that has problem in Linuxes from certain manufacturers. Either disable N or install through ndiswrapper the driver from your win8 disk.
Comment: I had the same problem, and I could solve it by installing the driver trough ndiswrapper, good suggestion!

Can't connect to specific wifi network


Spring Boot MongoRepository unit testing using pre-installed MongoDB

Question: I have a regular Spring Boot application (1.3.2) with MongoDB using MongoRepository.
I would like to write an integration test for one of my endpoints that gets the data from the MongoDB. As far as I see from the Spring Boot 1.3 Release Notes Spring has auto-configuration for Embedded MongoDB (de.flapdoodle.embed.mongo). However, I cannot figure out from Spring and flapdoodle documentation on how to write an integration test that would use already installed version of MongoDB on my filesystem.
So far my integration test looks like this:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class) // my application class
@WebAppConfiguration
public class IntegrationTest {

    @Autowired
    private MyRepository myRepository;

    @Before
    public void setup() {
        myRepository.save(new MyEntity());
    }

    @Test
    public void test() {
        // here I will fire requests against the endpoint
    }
}

I have added two dependencies with test scope: spring-boot-starter-test and de.flapdoodle.embed:de.flapdoodle.embed.mongo. So when I run the test, I can see that flapdoodle attempts to download version of MongoDB, but fails since I am behind the proxy. But I do not want to download any versions, I want it to use my locally installed MongoDB. Is it possible to do this?
Comment: did you done with these.
Answer: If you want to use your locally installed MongoDB (not recommended, since then the tests depend on a particular DB that can get into a dirty state), then you shouldn't be pulling in the embedded MongoDB.
I believe this config will do what you're asking for, though (seems to work in my Spring Boot 1.3.5 test):
import java.net.UnknownHostException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;

@EnableAutoConfiguration(exclude = MongoAutoConfiguration.class)
@Configuration
public class TestConfig
{
    @Primary
    @Bean
    MongoClient mongoClient()
    {
        try
        {
            return new MongoClient("localhost", 27017);
        }
        catch (UnknownHostException e)
        {
            throw new RuntimeException(e);
        }
    }
}

However, I suspect you would be better off properly configuring the proxy and using the embedded mongoDB in your tests. See this answer for hints on how to do that.


Trouble with escape character in WMI query

Question: processName.Name = @"\\dfs\ns1\Application_Data\tiny\Development\tinyLOS\tinyLOS.exe";

string wmiQuery = string.Format("select CommandLine from Win32_Process where PathName='{0}'", processName.Name);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();

I am trying to run the above code in C# using WMI but i keep getting an invalid query error when it executes. I suspect it's a problem with escaping the back slash but i thought i had accounted for that with the @. Am i missing something simple because this looks like it should execute ok?
(Note: the query executes when the back slashes are removed)
Comment: You should provide more information related to error.
Answer: You need to pass escaped slashes and it's ExecutablePath not PathName
wmiQuery = @"SELECT CommandLine FROM Win32_Process WHERE ExecutablePath =
            'C:\\Program Files\\Microsoft Security Client\\msseces.exe'";

var searcher = new ManagementObjectSearcher("root\\CIMV2", wmiQuery);

foreach (ManagementObject queryObj in searcher.Get())
    Console.WriteLine("CommandLine: {0}", queryObj["CommandLine"]);

For

CommandLine: "C:\Program Files\Microsoft Security Client\msseces.exe" -hide -runkey


Are long checkbox labels a problem?

Question: I'm working on an admission application page and in one section of it there is a list of checkbox controls indicating the user has read/agreed to various policies or conditions and certifying the information is correct. Some of these labels can be rather long wrapping to 2, 3 or 4 lines depending on the screen size.
Each of the checkboxes are setup similar to:

    <input type="checkbox">
    I certify that all the above information is correct yada yada yada...

While developing the page, one thing that kept happening that I found annoying was I'd accidentally check or uncheck boxes by clicking the label when changing focus from my editor to the browser.  When clicking to focus the browser I'd happen to hit one of these long labels.
That got me thinking about shorting the actual  tag to only encompass the first few words, or first sentence if there are multiple. For instance
<input type="checkbox" id="certify">
I certify that all the above information is correct yada yada yada...

Is it worth considering shortening the label like that to avoid accidental changes, or should I just leave it as is?
In this particular case all the checkboxes are required, so accidentally un-checking one would be caught by validation. However I wonder if this could be an issue for an optional but important checkbox.
Comment: On Windows, I learned to use `Alt`+`Tab` / click only in safe areas long time ago (after several frustrating mistakes). And this doesn't happen on Mac - when you click on a non-active window, it only activates, it does not trigger any events on individual elements...
Answer: I don't believe it's an issue, however, if you're worried about it, you could rephrase each statement to have the assertions ("The above is correct and yada yada...") followed by the checkbox with "I agree" as the label.
I'd watch how people use your page and see if any of them have this problem before trying to fix a problem that may or may not exist "in the wild."
Answer: If you could add a line break, you can limit the  to only 1 line. Or if you don't use the label at all, the user would have to click on the check box itself and that would be solve the problem in a consistent way.
However, splitting the label in the middle of a sentence is a bit strange - still possible to click on it by accident, while clicking a little bit to the right on purpose would not select anything...
The question is if clicking by accident is an important problem to solve - how often do you expect real users to go outside of the browser in the middle of completing the form? Have you tested with potential users or only noticed this yourself while developing the app and switching from IDE to browser?
Answer: A checkbox label should be max. 100 chars long.
If you need more, you could add a "Read more..." button.
It think this is a better method then throwing 5 copies of Lorem Ipsum to the user every time they need to use a checkbox.
Comment: Where are you getting this guideline from?
Comment: Also, the checkboxes he describes in his example are certifying that users have read/agree to certain terms or verifying that information is accurate. These statements are often legally binding, so the "Read more" suggestion would not work.
Comment: @maxathousand I get it from pure experience as being a user and a developer.
Answer: I would consider a long label a problem: people don't usually read long text, especially if it is some legalese.
But not for the reason you specify in the OP: accidental clicking is not an issue, especially  when all checks are required.
I have seen on multiple occasions companies giving me the one single check box, saying "I agree to (this site) (link: privacy policy) and (link: terms of service)" (add as many further links nobody will ever click as you wish ;) )
This form keeps the label short and gives the user an opportunity to obtain a full description of what they are aggreing to, if they so wish.

Are long checkbox labels a problem?


Can't get Canon scanner to work with Ubuntu 18.04

Question: Canon DCR225 Scanner
After installing Ubuntu 18.04 (clean install) I can't get my scanner to work. I am trying to use gscan2pdf, but after it detects the scanner, the scan button is greyed out.
On my other laptop (Ubuntu 16.04) it works fine.
Any idea what can cause this?
Comment: Hi obelix, I have a Canon scanner too, although a much older model. Are you connected via USB cable or is it a networked device? Just curious, any reason you are not using Simple Scan? You can save your scans as a multiple page PDF. If you have tried Simple Scan and it didn't work, and you are using a USB connection, honestly, I would suggest just unplugging the USB cable, turning off the printer completely, turning it back on, and reconnecting. I often have to do this, sometimes in between jobs, with my Canon and it stinks,
Comment: but it's better than not being able to print or scan at all. I've ended up not being able to use my Canon in past installations where I tried messing around with other drivers, using Gutenprint, pretty much every option out there.
Answer: so this device is probably the DR-C225
https://www.usa.canon.com/internet/portal/us/home/products/details/scanners/document-scanner/imageformula-dr-c225
Canon supply a driver;
go here https://www.canon-europe.com/support/products/document-scanners/dr-series/imageformula-dr-c225.aspx?type=drivers&language=EN&os=Linux%20(64-bit) and download d15106mux_Linux_v10_DRC225_DRC225W_64bit.zip
if you save it to your Downloads folder; then if you open a terminal and copy the commands below; and paste them into a terminal; (hit the ENTER key after each paste ..)
<code>cd Downloads

unzip d15106mux_Linux_v10_DRC225_DRC225W_64bit.zip

cd DR-C225_LinuxDriver_1.00-4-x86_64/x86_64

sudo dpkg -i cndrvsane-drc225_1.00-4_amd64.deb
</code>
.. so you need your sudo password for the last command .. and that .... should ... install the driver; and then xsane or simple scan should "see" the scanner and get it to run

SANE, the open-source place for scanning; lists this device as UNTESTED; so you could help them by contacting them https://alioth-lists.debian.net/cgi-bin/mailman/listinfo/sane-devel so you could join the mailing list; please help them
Answer: I just changed Grub line enabling USB 3 - https://ubuntuforums.org/showthread.php?t=2336077. Works fine.


Not able to use pretrained VGG16 model in Fastai

Question: I am using following code to call vgg16 pretrained model in fastai after reading documentation in Pytorch Vision Model
import fastai
from fastai.vision import *
from fastai.callbacks import *
learn6= cnn_learner(data, models.vgg16, metrics =[accuracy])
from fastai.callbacks import *
EarlySC = EarlyStoppingCallback(learn=learn6, monitor='accuracy', min_delta=0.01, patience=20)
reduceLR = ReduceLROnPlateauCallback(learn=learn6, monitor = 'accuracy', patience = 20, factor = 0.2, min_delta = 0)
learn6.fit(100,0.001,callbacks=[reduceLR,EarlySC])
learn6.save('vgg16')

But it throws following error:
AttributeError                            Traceback (most recent call last)
<ipython-input-38-e9aca7dabc9d> in <module>()
      5 from fastai.callbacks import *
      6 #model = torch.hub.load('pytorch/vision:v0.5.0', 'vgg16', pretrained=True)
----> 7 learn6= cnn_learner(data, models.vgg16, metrics =[accuracy])
      8 from fastai.callbacks import *
      9 EarlySC = EarlyStoppingCallback(learn=learn6, monitor='accuracy', min_delta=0.01, patience=20)

AttributeError: module 'fastai.vision.models' has no attribute 'vgg16'

Answer: You need to use "models.vgg16_bn" instead of "models.vgg16" and it will work.
cnn_learner(data, models.vgg16_bn, metrics =accuracy)

See documentation for more.


tablesorter pager initial pagination

Question: This might sound like a very stupid question to some of you, but I assure you I've been checking through the internet and I haven't had any luck about this. My question is: is it possible to set an initial pagination number in the tablesorter pager plugin? By default it takes the 10 option, but I've tried to put a 5 as the selected option and it loads 10 anyway. If I change it and come back to the 5 it will load as said, 5, but not at the beggining.
Is there any option when loading the tablesorter? My code for the tablesorter is this:
$("#TST").tablesorter({
        headers: { 0: { sorter: false }, 4: { sorter: false }, 5: { sorter: false }, 6: { sorter: false} },
        sortList: [[1, 0], [2, 0], [3, 0]],
        widgets: ['zebra']
    })
  .tablesorterPager({
        container: $("#TSTPager"),
        positionFixed: false //,
        //pagesize: 5
});

the pagesize attribute I wrote in the tablesorterPager was a test, but it doesn't do what I want it to.
Comment: I've never used the paging plugin for tablesorter, but if you don't get a solution, maybe try http://www.datatables.net/
Comment: thank you for the comment. I've been taking a look at what you sent me and it looks great and quite easy to handle, but for the moment, I'm trying to fix this, because my whole application is using tablesorter pager.
Answer: In the .tablesorterPager call specify a variable size:
example :-
.tablesorterPager({container: $("#pager"), size: 20});

Comment: I tried this, but it seems not to work. Has the keyword 'size' changed?
Comment: `size` is also not working for me -- even if I change it in the `jquery.tablesorter.pager.js` file.  I get 10 rows.  No matter what.
Answer: In jquery.tablesorter.pager.js file it'll be 10 size in your js file so change it to 5 like below in defaults variable block.
this.defaults = {
  size: 5
}

Answer: I had the same issue with the $.tablesorter.storage at first. Try the savesPages at false
.tablesorterPager({
   container: $(".ts-pager"),

   size: 5,
   savePages : false,
})

Actually, I dig in the javascript source code and find that the pager settings is stored in the tablesorter storage widget.
Comment: Welcome to SO! Even if your answer solves the problem, it is unclear as to why it might help. Please elaborate on what happens if you pass false with this parameter, and explain how it solves the issue.
Comment: This sounds like something you should add in your answer rather than in a reply to me. Try editting your answer.
Answer: $('document').ready(function(){
   $(".pagesize").val(50);
}

tablesorter pager initial pagination


Yii2 many to many relation. How to select with condition?

Question: There are two models:
Dish and Ingredient.
They have relation many to many.I need to get Dishes where ingredient_id = 1,2,3.
How to do it?
Answer: You should add the relevant code that is involved with the problem listed and view and controller action should be added to get the exact response.
The most basic way you can get the dishes having the ingredients [1,2,3] is using the Model
Dishes::find()->where(['IN','ingredient_id',[1,2,3]])->all();

The relations cannot be used in the current requirement they are used to get related records for one model inside another for instance if i have to get all the ingredient of a Dish with the id 1 and I have a relation defined with the Ingredient Model with the name getIngredients() i would do
$model=Dishes::findOne(1);
$ingredients=$model->ingredients;


What's the use of the 'parent: item/generated' in making texture packs?

Question: I've been making a texture pack for a datapack in Minecraft 1.14.
In the .json file for the items (where I allocate the path for the textures I think), I've been using:
<code>"parent": "item/template_spawn_egg",
</code>
but when I came to search for an issue with the spots, I found that they used a different parent:
<code>"parent"   : "item/generated",
</code>
I saw this being used in various places online and I assumed they're for a specific type of item or something. But seeing it being substituted like this got me curious: is the parent 'generated' a handy catch-it-all term which I can use in place of a regular parent, or is it something else more complicated?
Comment: Maybe it's used for the colours of spawn eggs.
Comment: Well its not Fabian, the colours of the spawn eggs are hardcoded in, that however can be disabled in pack.mcmeta I think.
Comment: To clarify to anybody looking in on this, the colour of the spots of the spawn egg are on a second layer, which the colour change are hardcoded for I'm pretty sure. for more info just scroll down to the answer below instead of reading my comments here
Answer: When you specify a parent model, the model you are currently creating will inherit properties from its parent.
This is especially useful if you are writing a custom model and you only want to modify one specific property of the model and keep all the other properties as default.
Example:
this can be your main torch model (the parent) and let's call the file "torchModel.json"
<code>{
    "ambientocclusion": false,
    "textures": {
        "particle": "#torch"
    },
    "elements": [
       {
           "from": [ 7, 0, 7 ],
           "to": [ 9, 10, 9 ],
           "shade": false,
           "faces": {
               "down": { "uv": [ 7, 13, 9, 15 ], "texture": "#torch" },
               "up":   { "uv": [ 7,  6, 9,  8 ], "texture": "#torch" }
       }
   },
   {
       "from": [ 7, 0, 0 ],
       "to": [ 9, 16, 16 ],
       "shade": false,
       "faces": {
           "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#torch" },
           "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#torch" }
       }
   },
   {
       "from": [ 0, 0, 7 ],
       "to": [ 16, 16, 9 ],
       "shade": false,
       "faces": {
           "north": { "uv": [ 0, 0, 16, 16 ], "texture": "#torch" },
           "south": { "uv": [ 0, 0, 16, 16 ], "texture": "#torch" }
           }
   }
  ]
}
</code>
and now you can have a custom model which inherits all the properties from the parent model like this:
<code>{
   "parent": "block/torchModel",
    "textures": {
       "torch": "block/torch"
     }
}
</code>
this custom model will use the torch block texture for the torch itself and it will still have the particles even though you didn't specify the particle property in the custom model file. The reason why it will have those particles is that they are specified in the parent file and the custom file is inheriting that property.
if you want a fully custom model with a custom shape and everything, you don't have to inherit from anything, you can just create the model from scratch, example:
<code>{
    "credit": "Made with Blockbench",
    "textures": {
        "0": "blocks/beacon",
        "particle": "blocks/beacon"
    },
    "elements": [
        {
            "from": [0, 0, 0],
            "to": [1, 1, 1],
            "faces": {
                "north": {"uv": [0, 0, 1, 1], "texture": "#0"},
                "east": {"uv": [0, 0, 1, 1], "texture": "#0"},
                "south": {"uv": [0, 0, 1, 1], "texture": "#0"},
                "west": {"uv": [0, 0, 1, 1], "texture": "#0"},
                "up": {"uv": [0, 0, 1, 1], "texture": "#0"},
                "down": {"uv": [0, 0, 1, 1], "texture": "#0"}
            }
        }
    ]
}
</code>
I hope this made sense, it is hard to explain something like this through text. More info can be found on the Minecraft wiki: https://minecraft.wiki/w/Model
Comment: Oh I see, when you want to create a new texture without the properties of the said parent, you use "item/generated" in parent as it will act as a blank slate without any additional properties such as an image overlay (which I had issues with currently). When I used the "item/template_spawn_egg" as the parent it will inherit the properties meaning it could save time in creating the resource pack as it takes out the need to program those properties in. I got it thanks


How to wire a Hunter Remote Ceiling Fan (Exeter) and utilize both wall switches

Question: I want to install a Hunter Exeter fan. The fan is remote operated for both lights and fan speed, however, I have two switches on the wall - one for the fan and one for the light.
I would like one of the switches to turn on the light, and the other to provide power for the fan (which I can then use the remote to control).
Here are the installation instructions
Diagram 1: This is my 'hack' attempted at it. Left switch goes directly to the light, the right one powers the fan.

Diagram 2: Below this is the version the manual says. I'm not sure which functions the yellow and blue wires from the receiver, so I'm taking a guess in Diagram #1. I don't like this one because the right switch is a dud after you've wired it.

**Update 8/15
I finally got around to wiring the fan, and the experts here on stackoverflow were right. The blue wire from the fan goes directly to the black wire from the ceiling to turn on the light directly from the switch. And yellow wire from the reciever connects directly to the black wire on the fan. Both switches work! I capped off the blue wire from the receiver.
Important Note: You might need to wire it per the manual first to make sure the light on the fan is turned on from the remote. The fan remembers the last setting and when powered goes back to that setting.**
Comment: Verify that the blue wire is for the fan. Blue is usually for the light fixture.
Comment: Can you post a functioning link to the manual for your fan? (Hunter's website is horribly broken :/)
Comment: Assuming blue wire is for the fan, does the diagram look feasible? It's either blue or yellow, but part of me wonders if it will short circuit the receiver if i do it wrong. https://a.sellpoint.net/a/Exeter+English+owner%27s+manual.pdf.pdf?spworld_assetname=rYB7lXeG.pdf&spworld_download=1&spworld_filename=Exeter%20English%20owner%27s%20manual.pdf.pdf
Comment: @michaelw -- how deadset are you on using the receiver that came with the fan?
Comment: @ThreePhaseEel the remote is the only way to adjust the speed on the fan (no fan chains), so if I direct connect the wire, we will have no control over the speed.
Comment: @michaelw -- I'm asking because oftentimes, the fan remotes that come with fans are horribly inflexible, leaving you better off with something else for a fan controller
Comment: Is the power from the two wall switches be controlled by dimmer switches? Or wall switches on or off?
Answer: That should be fine. The receiver shouldn't care or be hurt if the light kit isn't connected to it (it's the exact same situation, electrically, as not installing light bulbs or having the bulbs burned out).
Be sure to cover the light wire from the receiver securely - put one of the supplied wire nuts on it tightly, then secure with electrical tape so it doesn't fall off.
If it's not clear from the instructions which wire on the fan is for the motor and which is for the light, you could try powering each (one at a time) and the white with a cord and plug before you hang the fan. Do it before you install the blades and you won't have to worry about hitting anything if you happen to find the fan wire first.
Comment: A) if you're concerned that the wire nut is going to fall off either the nut is too big or it's not screwed on tight enough. A tug on the wire & nut should not separate them. B) Every fan I've ever installed (from different manufacturers) has always been a "blue light" special. i.e. the blue internal wiring is for the lights while black or red is for the fan.
Comment: Agree that tape should never be needed for a properly-done wire nut on multiple wires (especially solid), but getting one to stay on a single stranded wire is a bit iffy.
Comment: You _did_ get my up vote, I made the comment more for anyone reading the answer than for you.


Position shape at exact spot on ImageView

Question: I can't get the elements to position correctly on my layout in Android Studio. I have an ImageView with a png background containing the number 2. I have two Views each containing a small circle. I want the circles to always align at each tip of the number two. I can align them correctly on one device but the alignment changes on a different device. Is it possible to make these always align correctly in every device?
Here is what I want it to look like:
https://i.stack.imgur.com/v7nsg.png
Here is my code to calculate the one of the dots position:
    circle2 = findViewById(R.id.circle2);

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int heightPixels = metrics.heightPixels;
    int widthPixels = metrics.widthPixels;

    //dimensions of background image: 547x839

    dot2H = (heightPixels / 547) * 70;
    dot2W = (widthPixels / 829) * 70;
    dot2Hposition = (heightPixels / 829) * 500;
    dot2Wposition = (widthPixels / 547) * 300;
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) circle2.getLayoutParams();
    params.height = dot2H;
    params.width = dot2H;
    params.leftMargin = dot2Wposition;
    params.topMargin = dot2Hposition;
    circle2.setLayoutParams(params);

Here is the layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="net.beauvine.animationtest.MainActivity"
tools:showIn="@layout/activity_main">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"

    android:src="@drawable/two"
    android:id="@+id/imageView"
    android:padding="10dp"
    android:layout_alignParentEnd="false"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true" />

<RelativeLayout
    android:id="@+id/dotLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="center"
    >

    <View android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/circle2"
        android:background="@drawable/circle"
        android:clickable="true"
        android:alpha=".8"
        />
    <View android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/circle"
        android:background="@drawable/circle"
        android:clickable="true"
        android:alpha=".8"
        />

</RelativeLayout>

Answer: Android is used on a very large number of devices with very different screen sizes and density. Because of this it's hard to do what you want via xml layout. But you can use layout with fixed relations of views so it will look similar to what you want but this isn't good approach.
This example can give you a key. This layout shows 4 views in
exact places of screen always.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="2">

        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <View
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@android:color/white" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <View
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@android:color/white" />
        </FrameLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="2">

        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <View
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@android:color/white" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <View
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@android:color/white" />
        </FrameLayout>
    </LinearLayout>

</LinearLayout>

Something like this one:

Better if you will draw both background (with number 2) and circles in custom view. So you'll know exact sizes and coords of all object and can place them correctly.
Just example of drawing in custom view:
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    public class MyView extends View {
        public MyView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);

            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.BLACK);
            canvas.drawPaint(paint);

            paint.setColor(Color.WHITE);
            canvas.drawCircle(x / 2, y / 2, radius, paint);

            paint.setColor(Color.WHITE);
            canvas.drawCircle(x / 3, y / 3, radius, paint);
        }
    }
}

Hope this helps.
Comment: I have been trying out your custom view suggestion and it seem to be getting me closer to my goal. However, one thing that I did not clarify before is that the dots are buttons that animate when you touch them. How do I incorporate that? In your example you drew circles on a canvas. Unfortunately, those cannot be buttons.
Comment: You need to create specific object which will draw itself and handle touch action (like View). Do you programming something like a game? In this case you can try to use one of free game engines. They all support custom drawing, animation of objects, necessary interaction etc.
Comment: Thanks for the help! I ended up making another custom view for each dot and I made those into buttons. Your solution definitely got me on the right path.


What causes a breaker to trip?

Question: In a normal, properly-wired home, what are the possible causes of a tripped breaker? At 110-120V is there a maximum wattage throughput on a single breaker?
I'd like to understand the system to be able to know how best to lay out the electrical system in a brand new house. I'm not an electrician, but I do understand certain basic concepts. (I'm also not planning necessarily on doing the work myself, but I'd like to understand the whole line of thinking behind electrical system layout.)
Comment: When planning circuits, you'll typically only want to load the circuit to 80%.  So for a 15A circuit @ 120V, you'll only want to have ~1440 Watts. You also have to consider that this is in a perfect world, where the voltage is always 120V. In the real world, a *good* supply will be +- 5%, so you could be anywhere from 114V to 126V (@80% = 1368 - 1512 Watts).
Answer: Short-circuit Protection
A breaker that offers short-circuit protection, will trip if there is a short somewhere in the circuit.  A short-circuit is characterized by a very high current increase in a very short period of time.  This type of protection is usually provided by an electromagnetic device; commonly an electromechanical solenoid, which physically opens the circuit when a short-circuit is detected. Most residential short-circuit protection devices trip at 10 kA (10,000 A).
Overcurrent Protection
Breakers that offer overcurrent protection, trip when a current higher than the rated current is drawn through the device over a specific amount of time. An overcurrent situation is usually detected using heat, and so is slower acting than short-circuit protection.  Overcurrent protection is usually provided by a bimetallic strip, which trips the breaker if it is heated too much for too long.
Most typical residential circuit breakers are combination devices, and offer both short-circuit and overcurrent protection. Wikipedia has a great image of the inside of a circuit breaker, which shows both short-circuit and overcurrent protection mechanisms.

5 - Bimetallic strip providing overcurrent protection.
7 - Electromechanical solenoid offering short-circuit protection.

Ground-fault Protection
Ground-fault protection is a recent addition to circuit breakers, which offers protection to people and equipment.  Breakers that offer ground-fault protection, trip when the current flowing out to the circuit is higher than the current returning from the circuit.  A current transformer (CT) inside the breaker, is a common way used to measure current imbalances.  The CT will be wrapped around both conductors, and if a large enough current is induced on the CT the breaker will open the circuit.  Residential ground-fault circuit breakers are almost exclusively combination devices offering short-circuit, overcurrent, and ground-fault protection.
Arc-fault Protection
Arc-fault protection is the most recent addition to circuit breakers, and offers protection against dangerous electrical arcs. They use complex electronics to analyze the circuit looking for tell tale signs of dangerous electric arcs, all the while ignoring non-hazardous arcs.  As with ground-fault circuit breakers, arc-fault breakers are almost always combination devices as well.
Answer: Breakers trip when an overcurrent condition occurs. That's it.
With some caveats we can ignore, overcurrent = load greater than the breaker's rating. For example, if you draw 50A on a 15A breaker, it will trip.
However, overcurrents can be considered in two groups.
Some are effectively infinite - an infinite draw on a breaker of any size is always an overcurrent. This happens when there's a short circuit, for example if a rodent chews through the hot wire in the wall, and it touches ground. If you're getting a short circuit in your home wiring, a repair will be required.
The other kind is typically within the same order of magnitude of the breaker's rating, for example if you put three tea kettles on the same circuit in your kitchen. You want the breaker to trip here, too, but it's annoying. This is the user's error, and can be remedied by putting devices on separate circuits, or only running 1 at a time, etc.
In all cases, the purpose of the breaker is to protect the in-wall wiring for that circuit. If the breaker did not trip, then the wire would act as a fuse, heating up, and eventually melting to break the circuit. A fire might have started in the meantime.
Usually a breaker is at the beginning of a circuit, but the main breaker for a panel (or subpanel) is often at the end of the circuit. That means that flipping the breaker off will not de-energize the wire it is protecting.
Comment: So, TL;DR: A breaker trips when there's more amperage draw than is allowed/rated by the breaker itself?
Comment: Unless we're talking about a GFCI or AFCI breaker.
Comment: Most breakers trip just shy of infinity, usually around 10kA.
Comment: Exactly right. ***
Answer: Circuit Breakers are rated in Amps and fail open when the rating is exceeded.
Excessive current causes heat, leading to fire danger.
If you're going to base your calculations on wattage, you have to know the formula.
Power (Watts) = EMF (Volts) & I (Current)
P/E = I or 3000W/120V = 25A
Plugging two 1500 watt hair dryers into a single circuit and using both on high will do it. 3000 Watts @ 120V = 25A and your circuit breaker will usually be 20A. You're 5A over limit, so pop.
Same goes for using a 2250W (3 hp) motor on the circuit, but the problem here is the inrush current during motor start will pop the breaker as will bogging the motor down (current increases as back-emf decreases)
So, too many devices on the circuit, or not having the appropriate dedicated circuit for a high power device will lead to current drawn exceeding the breaker's rating.
Maximum Wattage for common house wiring circuits, split phase:
<code>240V @ 50A = 12000W
240V @ 30A =  7200W
240V @ 20A =  4800V

120V @ 30A =  3600W
120V @ 20A =  2400W
120V @ 15A =  1800W
</code>
Comment: @TKKocheran Breakers are sized to protect the wire in the circuit from overheating. You *could* install 30A breakers on every circuit, but then you'd have to use the appropriate sized wire.  This is almost always cost prohibitive. There is also the problem that you'd have to modify all of your cord-and-plug devices (Radio, TV, etc.), to allow them to be plugged in to a 30A receptacle.
Comment: Is there a reason why using a lower-amperage breaker would be appropriate? Is there a certain type of wiring which is necessary for higher-load applications? ie: why wouldn't I wire my entire house with 30A breakers? If it's because of heat, can't I use better insulated wire to work around the problem?
Comment: You need to break out the NEC and start studying why things are done the way they are. Yes, you could oversize the wire on everything, no, it wouldn't pass code inspection is the short, succinct answer. Explanation would run into tldr; we've arrived at doing things so they fail safe, excessive copper and amperage available where it shouldn't be allows things to fail disastrously.
Comment: @FiascoLabs NEC does not give you the *why*, it only gives you the *how*.  The *why* according to NEC, is because they say so.

What causes a breaker to trip?


MySQL - How to select data based on another select (subselect?)

Question: It is only my second Query and I wonder, is there any chance to get what I need.
I'am working with Prestashop and I would like to export data about the product.
With the select "GROUP_CONCAT(DISTINCT ac.id_product_2)" I'am getting the product (which I need) ID, but I would like to get the product reference based on these ID.
I wonder, is there any change to get the product reference based on those ID?
My query is:
SELECT p.id_product, pl.name, p.reference, p.mcompleted,pl.description_short, pl.meta_title,
pl.link_rewrite, GROUP_CONCAT(DISTINCT ac.id_product_2)
FROM ps_product p
LEFT JOIN ps_product_lang pl ON (p.id_product = pl.id_product)
LEFT JOIN ps_stock_available s ON (p.id_product = s.id_product)
LEFT JOIN ps_accessory ac ON (ac.id_product_1 = p.id_product)
WHERE pl.id_lang = 2
AND p.active = 1
AND s.quantity > 0
AND p.id_product > 35000
AND p.mcompleted = 1
GROUP BY p.id_product

Right know I'am getting the data something like this:
id_product     reference     GROUP_CONCAT(DISTINCT ac.id_product_2)
 35026           21-176F      35026,35027
 35027           55-FFFF      35027,35028
 35028           66-FFFF      35026,35028

But I would like to get something like  this:
id_product     reference     GROUP_CONCAT(DISTINCT ac.id_product_2)
 35026           21-176F      21-176F,55-FFFF
 35027           55-FFFF      55-FFFF,66-FFFF
 35028           66-FFFF      21-176F,66-FFFF

Already spent 6+ hours on internet, hoping for Your help :)
Answer: Assuming the ac.id_product_2 also links to the ps_product table then you could simple make another join and concatenate the reference instead of the id.
SELECT p.id_product, pl.name, p.reference, p.mcompleted,pl.description_short, pl.meta_title,
pl.link_rewrite, GROUP_CONCAT(DISTINCT p2.reference)
FROM ps_product p
LEFT JOIN ps_product_lang pl ON (p.id_product = pl.id_product)
LEFT JOIN ps_stock_available s ON (p.id_product = s.id_product)
LEFT JOIN ps_accessory ac ON (ac.id_product_1 = p.id_product)
LEFT JOIN ps_product p2 on (p2.id_product = ac.id_product_2)
WHERE pl.id_lang = 2
AND p.active = 1
AND s.quantity > 0
AND p.id_product > 35000
AND p.mcompleted = 1
GROUP BY p.id_product

Comment: It worked! For more than 2 weeks I have wondered how should I get the data I need... Just save another two weeks of wondering. Thank you very much!


VBA Run-time error 3075

Question: I'm trying to write an SQL query in VBA but it's not working. Not sure why, its a simple SELECT query. Below is my SQL query:
strSQLPharmContact = "SELECT TOP 1 tbl_Contacts.ID,
tbl_Contacts.idSite, tbl_Contacts.role, tbl_Contacts.name,
tbl_Contacts.email, tbl_Contacts.phone, tbl_Contacts.involvement,
tbl_Contacts.Taken" _ & "FROM tbl_Contacts " _
& "WHERE (((tbl_Contacts.role)= 'Pharmacist') AND
((tbl_Contacts.involvement)=True) AND ((tbl_Contacts.Taken)=False)); "

Cheers guys
Comment: Include `Debug.Print strSQLPharmContact`, run the code and then examine the statement it built.
Answer: Most probably the error is because of spacing issue in your query. You need a space as shown below
& " FROM tbl_Contacts " _
   ^---- Here

Otherwise, your query string looks like
SELECT TOP 1 tbl_Contacts.ID, tbl_Contacts.idSite,
tbl_Contacts.role, tbl_Contacts.name,
tbl_Contacts.email, tbl_Contacts.phone,
tbl_Contacts.involvement, tbl_Contacts.TakenFROM tbl_Contacts
                                            ^-- ERROR Here

Answer: Why so many brackets?
When using VBA to hit a DB, I always like to structure my SQL query so it looks exactly like I would enter it into an SQL Query tool.
Run and have a look in the debug window (ctrl-g)
Much neater and as a result much easier to modify and trouble shoot:
Sub sql()
    strSQLPharmContact = "SELECT TOP 1 tbl_Contacts.ID,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.idSite,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.role,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.name,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.email,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.phone,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.involvement,"
    strSQLPharmContact = strSQLPharmContact & vbLf & "       tbl_Contacts.Taken"
    strSQLPharmContact = strSQLPharmContact & vbLf & "FROM   tbl_Contacts "
    strSQLPharmContact = strSQLPharmContact & vbLf & "WHERE  tbl_Contacts.role= 'Pharmacist'"
    strSQLPharmContact = strSQLPharmContact & vbLf & "AND    tbl_Contacts.involvement = True"
    strSQLPharmContact = strSQLPharmContact & vbLf & "AND    tbl_Contacts.Taken = False"
    Debug.Print strSQLPharmContact
End Sub

VBA Run-time error 3075


Is it possible to trade Seraph weapons with a player that doesn't own the Captain Scarlett DLC?

Question: Seraph weapons sound like great guns, but I don't have the Captain Scarlett DLC.  On the other side, I've got a few friends who does.  Will I be able to exchange Seraph weapons with them (either by trading or simply dumping it on the floor) ?
Comment: I remember a message saying I don't have the DLC, I don't remember if I was trying to equip or pick up a seraph weapon though.
Comment: I'm pretty sure that you can - on the Xbox, you have to download a "compatibility pack" that contains all the new DLC's weapons and so forth.  They mention it being required to use the new guns in the DLC, and you don't have to pay for it.
Comment: Sounds really interesting, hope that someone will be able to confirm that asap !  PS: I'm playing with the PC version (if that's of any importance).
Comment: "Seraph weapons sound like great guns" Unfortunately, reality is not always how things sound.
Comment: How sad...  So... I don't need to cry because I don't have the said DLC ?
Comment: @agent86 don't think that's true; the compatability pack was for the Mechromancher's data and such (which is why it doesn't exist on PC)  so you can play *with* people with DLC items, but you still can't own them yourself (otherwise you couldn't play with anyone using Gaige unless you had the DLC yourself)
Comment: @BenBrocka, for every (season pass) DLC released so far, there's been a corresponding compatibility pack for the Xbox, and I thought it had mention of being able to play with them and having support for all the guns.  I'm not really in a position to test though, so I can't confirm (thus the comment(s))
Comment: @agent86: So that support is so that your friends can use their guns, not so you can use them.  I wouldn't be surprised if they did the same thing for BL1, as per my answer.
Comment: I've just tried (PC version): you can see the weapon, loot it, but you cannot equip it.
Answer:
Requires Pirate's Booty

I think that should be prety clear.  If you don't own the DLC, you aren't able to use the weapons that are introduced in that DLC.  This was the same case for Borderlands as well.
Comment: @Anto It's right there in your image.  As to whether you can even pick one up, I'm not sure, but you couldn't in BL1.


Unable to connect second monitor

Question: I am trying to connect my external auxiliary monitor with my primary display. I am running Ubuntu-18.04. I am connecting both monitors with onboard display ports. Ubuntu detects two monitors untill the login screen. Signal gets lost on external display after I am logged in. I tried removing ~/.config/monitors.xml but it doesn't work. Any help would be highly appreciated.
Answer: Steps Connect another monitor to your computer
Set up an additional monitor
To set up an additional monitor, connect the monitor to your computer. If your system does not recognize it immediately, or you would like to adjust the settings:

Open the Activities overview and start typing Settings.
Click on Settings.
Click Devices in the sidebar.
Click Displays in the sidebar to open the panel.
In the display arrangement diagram, drag your displays to the relative positions you want.

Tip- The numbers on the diagram are shown at the top-left of each display when the Displays panel is active.

Click Primary Display to choose your primary display.

Note: The primary display is the one with the top bar, and where the Activities overview is shown.

Select the resolution or scale, and choose the orientation.
Click Apply. The new settings will be applied for 20 seconds before reverting back. That way, if you cannot see anything with the new settings, your old settings will be automatically restored. If you are happy with the new settings, click Keep Changes.

Check this link might help you - https://help.ubuntu.com/stable/ubuntu-help/display-dual-monitors.html

Unable to connect second monitor


How to write a QueryOver for a hierarchy structure

Question: I have the following hierarchy in my database structure -

One JobOrder has Many Templates
One Template has Many Groups
One Group has Many Items
One Item has one Status and one Status has one Item (One to One)

I have mapped these tables to my models in NHibernate and it is also working correctly.
The one - to - one relationship has been mapped this way -
Item.hbm.xml:
<one-to-one name="Status" class="ItemStatus"></one-to-one>

Status.hbm.xml:
 <id name="Id" column="Id" type="long">
  <generator class="foreign" >
    <param name="property">Item</param>
  </generator>
 </id>
 <one-to-one name="Item" class="ItemInGroup" constrained="true"></one-to-one>

I want to write an nhibernate QueryOver which would return all the job orders which have atleast one item in its hierarchy whose status is null.
I tried writing the following -
var jobOrders =
            Repository.QueryOver<Models.JobOrder>().Where(
                jo => jo.Templates.Any(t => t.Groups.Any(g => g.Items.Any(i => i.Status==
                    null)))).List();

But it throws the exception -

Unrecognised method call: System.Linq.Enumerable:Boolean Any[TSource](System.Collections.Generic.IEnumerable1[TSource], System.Func2[TSource,System.Boolean])

How do I write this?
Answer: You need to use JoinQueryOver or JoinAlias.

Somthing like this should work (not tested, but you should get the idea):
var jobOrders = Repository
    .QueryOver<Models.JobOrder>()
    .JoinQueryOver<Models.Template>(j => j.Templates)
    .JoinQueryOver<Models.Group>(t => t.Groups)
    .JoinQueryOver<Models.Item>(g => g.Items)
    .Where(i => i.Status == null)
    .List<Models.JobOrder>();


Getting files/folders from sharepoint via the api in c#

Question: I'm trying to link a c# application to a sharepoint directory, so I can create folders, download and upload files. However I am strugling with connecting to the correct folder.
I can retrieve the content from allitems.aspx, but I am not sure how to actually get the content from folder.
I have tried using the ClientContext - something like this:
<code>        ClientContext cxt = new ClientContext("https://xx.sharepoint.com/sites/");

        cxt.Credentials = GetCredentials();

        List list = cxt.Web.Lists.GetByTitle("Kontrakter");
        var test = list.Views;
        var test1 = cxt.Web.Lists;

        cxt.Load(test1);
        cxt.Load(list);
        cxt.Load(test);
        var a = 4;

        var fullUri = new Uri("https://xx.sharepoint.com/sites/yy/Kontrakter/AllItems.aspx");
        //var folder = cxt.Web.GetFolderByServerRelativeUrl(fullUri.AbsolutePath);

        using (var rootCtx = new ClientContext(fullUri.GetLeftPart(UriPartial.Authority)))
        {
            rootCtx.Credentials = GetCredentials();
            Uri webUri = Web.WebUrlFromPageUrlDirect(rootCtx, fullUri);
            using (var ctx1 = new ClientContext(webUri))
            {
                ctx1.Credentials = GetCredentials();

                var list1 = ctx1.Web.GetList(fullUri.AbsolutePath);
                ctx1.Load(list1.RootFolder.Files);
                ctx1.ExecuteQuery();

                Console.WriteLine(list.RootFolder.Files.Count);

            }
        }
</code>
or via normal api calls like this:
https://xx.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Kontrakter/Forms')/Files
The only way I can find some data is if I look into 'Shared documents/Forms'
I'm having problems understanding the directory structure and how I can actually find the content of files/folders.
Thanks in advance :)
Comment: The old way is to use FTP GetDirectory (https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-list-directory-contents-with-ftp) or get from a shared folder using window methods.
Answer: Turned out I was missing a /sites in one of my uris.


Converting an OpenCV Image to Black and White

Question: How do you convert a grayscale OpenCV image to black and white? I see a similar question has already been asked, but I'm using OpenCV 2.3, and the proposed solution no longer seems to work.
I'm trying to convert a greyscale image to black and white, so that anything not absolutely black is white, and use this as a mask for surf.detect(), in order to ignore keypoints found on the edge of the black mask area.
The following Python gets me almost there, but the threshold value sent to Threshold() doesn't appear to have any effect. If I set it to 0 or 16 or 128 or 255, the result is the same, with all pixels with a value > 128 becoming white, and everything else becoming black.
What am I doing wrong?
import cv, cv2
fn = 'myfile.jpg'
im_gray = cv2.imread(fn, cv.CV_LOAD_IMAGE_GRAYSCALE)
im_gray_mat = cv.fromarray(im_gray)
im_bw = cv.CreateImage(cv.GetSize(im_gray_mat), cv.IPL_DEPTH_8U, 1);
im_bw_mat = cv.GetMat(im_bw)
threshold = 0 # 128#255# HAS NO EFFECT!?!?
cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);
cv2.imshow('', np.asarray(im_bw_mat))
cv2.waitKey()

Comment: what is wrong with `im_gray_mat<threshold`
Answer: Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:
1. Read a grayscale image
import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)

2. Convert grayscale image to binary
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

3. Save to disk
cv2.imwrite('bw_image.png', im_bw)

Comment: Note: At least in OpenCV 3.1 (and perhaps earlier), `cv2.CV_LOAD_IMAGE_GRAYSCALE` is now `cv2.IMREAD_GRAYSCALE`. Other than that, the code works perfectly using Python 3.5.
Comment: This may be out of the questions scope, but can you please explain what is the value 128 mean in the first code in 2 if the theshold value is be automatically selected?
Comment: There is nothing special about this value since as you say the threshold is automatically selected. The value is just ignored. See https://github.com/opencv/opencv/blob/master/modules/imgproc/src/thresh.cpp#L1510
Comment: How do you convert the binary obtained into a grayscale image using cv2 ?
Comment: When you use an THRESH_OTSU, automatically THRESH is automatically considered zero
Answer: Specifying CV_THRESH_OTSU causes the threshold value to be ignored. From the documentation:

Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu's algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu's method is implemented only for 8-bit images.

This code reads frames from the camera and performs the binary threshold at the value 20.
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, const char * argv[]) {

    VideoCapture cap;
    if(argc > 1)
        cap.open(string(argv[1]));
    else
        cap.open(0);
    Mat frame;
    namedWindow("video", 1);
    for(;;) {
        cap >> frame;
        if(!frame.data)
            break;
        cvtColor(frame, frame, CV_BGR2GRAY);
        threshold(frame, frame, 20, 255, THRESH_BINARY);
        imshow("video", frame);
        if(waitKey(30) >= 0)
            break;
    }

    return 0;
}

Answer: For those doing video I cobbled the following based on @tsh :
import cv2 as cv
import numpy as np

def nothing(x):pass

cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)

while(True):
    ret, frame = cap.read()
    vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    thresh = cv.getTrackbarPos('T','videoUI');
    vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]

    cv.imshow('videoUI',cv.flip(vid_bw,1))

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

Results in:
Answer: Approach 1
While converting a gray scale image to a binary image, we usually use cv2.threshold() and set a threshold value manually. Sometimes to get a decent result we opt for Otsu's binarization.
I have a small hack I came across while reading some blog posts.

Convert your color (RGB) image to gray scale.
Obtain the median of the gray scale image.
Choose a threshold value either 33% above the median

Why 33%?
This is because 33% works for most of the images/data-set.
You can also work out the same approach  by replacing median with the mean.
Approach 2
Another approach would be to take an x number of standard deviations (std) from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following:

th1 = mean - (x * std)
th2 = mean + (x * std)

Note: Before applying threshold it is advisable to enhance the contrast of the gray scale image locally (See CLAHE).
Comment: Thanks for sharing the (2).
Comment: could you show the code snippet to (2) obtain the median of a gray scale image?.
Comment: @thewaywewere Yu can use the function available in `numpy` like this: `np.median(gray_image)`
Answer: Simply you can write the following code snippet to convert an OpenCV image into a grey scale image
import cv2
image = cv2.imread('image.jpg',0)
cv2.imshow('grey scale image',image)

Observe that the image.jpg and the code must be saved in same folder.
Note that:

('image.jpg') gives a RGB image
('image.jpg',0) gives Grey Scale Image.
Comment: Grey scale is not black and white!
Answer: Pay attention, if you use cv.CV_THRESH_BINARY means every pixel greater than threshold becomes the maxValue (in your case 255), otherwise the value is 0. Obviously if your threshold is 0 everything becomes white (maxValue = 255) and if the value is 255 everything becomes black (i.e. 0).
If you don't want to work out a threshold, you can use the Otsu's method. But this algorithm only works with 8bit images in the implementation of OpenCV. If your image is 8bit use the algorithm like this:
cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);
No matter the value of threshold if you have a 8bit image.
Answer: Here's a two line code I found online that might be helpful for a beginner
# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)

image_8U = np.uint8(abs_image_in32_64)


org-mode exclude fullpage.sty from latex preview preamble

Question: Using fullpage.sty in a document preamble breaks latex preview by generating a full page preview images with page numbers. I.e., this code:
#+LATEX_CLASS: article
#+LATEX_CLASS_OPTIONS: [a4paper]
#+LATEX_HEADER: \usepackage{fullpage}

\begin{equation}
E=mc^2
\end{equation}

will generate the preview image:

How to exclude fullpage package from LaTeX preview preamble? Also, is it a bug and needs a bug report?
Comment: I have a feeling that this should go to the [TeX-LaTeX stack exchange forum](http://tex.stackexchange.com/).
Comment: Please also upload the image here. Your dropbox link will expire one day, and this question will stay.
Comment: Can't you just drop the `fullpage` from you preamble? Otherwise I don't understand the question...
Comment: Well, I need the fullpage.sty when export to PDF, but not need it when LaTeX preview. I.e. "just drop" is not a solving, but a hack.
Comment: @sdorof: It's clear then... I don't understand the question.
Answer: according to org-latex-preview#Minted if you add the fullpage.sty package to org-latex-packages-alist in your emacs configuration file like so:
(add-to-list 'org-latex-packages-alist '("" "fullpage" nil))

it should use it for exporting but not for the preview.


How to figure out where in a questline I am?

Question: I am trying to get my Legion flying, and for that I need the "A Glorious Campaign" achievement. However, I abandoned this long ago as I did not play much during Legion. Now I am trying to figure out where in the quest chain I am, and I'm totally lost. I use Carbonite, and am willing to use other addons to assist in the process. I am a Paladin, but an ideal answer would work for other classes trying to do other quest-lines
Answer: I've managed to solve my problem using two resources - first, an addon called Quest Completionist. It provides a very intuitive interface into my quest history - much more so than Carbonite, even if it has far fewer features. Second, I just look up the quest lines on Wowhead and search in there for the quests. Using a binary search I was able to quickly find the first quest in the chain I had not completed. I used this in multiple chains and the process was fairly smooth.


Trace optimization of a function of a left stochastic matrix

Question: I'm trying to find
$\max_X \text{tr}(AYBX^T)$,
where $A$ is $m \times m$, $B$ is symmetric $n \times n$, and $X$ and $Y$ are $m \times n$ left stochastic matrices. I'm specifically interested when this occurs for $X = Y$. I attempted using a Lagrangian with the constraints $XX^T - J = 0$ or $X^T1_m - 1_n = 0$.
$\mathcal{L} = \text{tr}(AYBX^T) - \text{tr}(\Lambda^T (XX^T - J)) \implies \partial_X \mathcal{L} = AYB - (\Lambda + \Lambda^T)X = 0$,
$\mathcal{L} = \text{tr}(AYBX^T) - \lambda^T(X^T1_m - 1_n) \implies \partial_X \mathcal{L} = AYB - 1_m \lambda^T = 0$,
but those don't seem to work (I know this because I know the answers to some examples). I'm probably doing something wrong that's quite basic, so my apologies. Does anyone have any hints or recommendations?
Thank you very much.
Comment: In the 2nd Lagrangian you are missing the nonnegativity constraints.
Answer: Let $C=AYB$ and consider the function
$$ \phi = {\rm tr}(CX^T) = C:X $$
where a colon denotes the Frobenius product, a convenient notation for the trace. It can also be written as elementwise/Hadamard multiplication followed by summation over all terms.
$$\phi = \sum_{ij}(C\odot X)_{ij}$$
To minimize $\phi$ find the smallest element in each column of $C$ and set the corresponding element of $X$ equal to one. Set all other elements of $X$ to zero.
To maximize $\phi$, locate the largest element in each column of $C$ and set the corresponding element of $X$ equal to one.
The described $X$ matrices are obviously stochastic and maximize (or minimize) the given objective function.
Comment: Thank you. I was trying to work out what you'd written before, since it didn't seem to match with my examples. From it, I realized that I'd missed a further constraint

$I \odot ((A - I^\dagger A)XBX^T) \geq 0$.

However, this makes sense from what I asked.
Comment: @Hruodland What is the $I$ matrix in your constraint? Is it the identity matrix, or something else?
Comment: $I$ is the identity, and $I^\dagger$ is the backward identity.
Comment: I can use the Karush-Kuhn-Tucker conditions for this. When the KKT multiplier, $\mu$, is 0, we can just use what you wrote above. Else, let $g = I \odot ((A - I^\dagger A)XBX^T) = 0$, and find $\partial_X \text{tr}(\phi - \mu g) = 0$.


Azure AD B2C example fail to compile for .Net Core 2.0

Question: I used this sample https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp for my .net core 1.1 web app. Now, I've been trying to make it work myself for .NET Core 2.0 but had no luck, too much unclear things in all this.
So, can anyone provide an example of how to use Azure AD B2C with ASP.Net Core 2.0?
Answer: A new branch was created with the version upgrade. It's a community submission and not yet tested by the product team but check it out: https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp/tree/core2.0
Comment: The specified link above is broken.


is my browser compatible for this web app (pwa)? whatwebcando

Question: Ive created a number of web apps (pwa's) each has its own feature requirements. Where i am falling short is with browser compatibility for my apps.
At the moment i am forcing the use of Chrome, Edge, Samsung browser and safari for ios.
If i check at https://caniuse.com it tells me, for example, Safari does not support background sync, and other browser's don't support other features. It does not say that chrome or edge on ios supports background sync or alternative browsers or versions to use.
Also there are many browsers each with their own following and different versions within each browser which do and do not support specific features. . I would like to support as many as possible.
What i would like to do is create/or download a script/plugin that when the user lands on the apps info page, the script will detect if the browser supports all the features required by the specific pwa, like service-worker.js, Geolocation, background sync, augmented reality, etc etc, and if it does, show the install button or recommend an alternative browser/version.
Something like||Exactly like the feature detection of https://whatwebcando.today/.
Is there a plugin or script already that can do this OR do i have to create my own from scratch?
I have tried searching for something, but all I'm getting is online tools and scripts like feature.js, which is limiting/limited and other websites like https://whatwebcando.today/
Answer: You could use Modernizr to do the feature detection and let the user know what features are supported, then update the page accordingly.
Modernizr.on('serviceworker', (result) => {
  if (result) {
    console.log('Service workers are supported.');
  } else {
    console.log('Service workers are NOT supported.');
  }
});

Comment: Hi Pete..I did look into modenizer after i asked this question.. You are correct its the best way.. For me though i try to avoid Plugins as much as possible.. Modenizer is quite big and complex and has all the possible features in it, of which most i don't and most probably will never use.. I decided to write my own function specific for PWA and here it is:
Answer: It seems i am allowed to post answers now:
here is my test function for browser compatibility:
var testArr;
function detectFeatures(registration) {
var win = window,
    doc = document,
    nav = navigator,
    scr = screen;
return {
    "Installable": "serviceWorker" in nav,
    "Home Screen": "relList" in HTMLLinkElement.prototype && doc.createElement("link").relList.supports("manifest") && "onbeforeinstallprompt" in win || "BeforeInstallPromptEvent" in win || "setAppBadge" in nav,
    "Installed Apps": "getInstalledRelatedApps" in nav,
    "Foreground Detection": "visibilityState" in doc || doc.visibilityState,
    "Freeze Detection": "onresume" in doc || "onfreeze" in doc,
    "Resume Detection": "onresume" in doc || "onfreeze" in doc,
    "Permissions": "permissions" in nav,
    "Network type": "connection" in nav || "mozConnection" in nav || "webkitConnection" in nav || "msConnection" in nav,
    "Network speed": "connection" in nav || "mozConnection" in nav || "webkitConnection" in nav || "msConnection" in nav,
    "Online state": "onLine" in nav,
    "Background Sync": "SyncManager" in win || "sync" in registration,
    "Periodic Background Sync": "periodicSync" in registration || "SyncManager" in win || "periodicSync" in win || "periodicSync" in nav,
    "Background Fetch": "backgroundFetch" in registration,
    "Task scheduling": "Notification" in win && "showTrigger" in Notification.prototype || Notification.prototype.showTrigger || "taskScheduler" in registration || "alarms" in nav || "periodicSync" in registration,
    "Notifications": "Notification" in win || "showNotification" in registration,
    "Push Messages": "PushManager" in win || "pushNotification" in win.safari || win.safari.pushNotification || "pushManager" in registration,
    "Offline Capabilities": "caches" in win,
    "Cache Support": "caches" in win,
    "Offline Storage": "localStorage" in win || "sessionStorage" in win,
    "Storage": "storage" in nav && "StorageManager" in win,
    "Persistent Storage": "storage" in nav && "persist" in nav.storage || "storage" in nav && "persisted" in nav.storage,
    "Storage Quotas": "storage" in nav && "estimate" in nav.storage,
    "IndexedDb": "indexedDB" in win || "mozIndexedDB" in win || "webkitIndexedDB" in win || "msIndexedDB" in win,
    "File Access": "File" in win || "chooseFileSystemEntries" in win,
    "File Api": "File" in win && "FileReader" in win && "FileList" in win && "Blob" in win || "chooseFileSystemEntries" in win,
    "Clipboard": "clipboard" in nav || "ClipboardEvent" in nav || "oncut" in doc || "onpast" in doc || "oncopy" in doc,
    "Pointing Device Apadtation": win.matchMedia("(pointer: none), (pointer: coarse), (pointer: fine)").matches,
    "Navigation Preload": "navigationPreload" in registration,
    "Contacts": "contacts" in nav || "mozContacts" in nav,
    "SMS": "messaging" in nav,
    "Geolocation": "geolocation" in nav,
    "Geofencing": "GeofenceManager" in win,
    "NDEFReader": "NDEFReader" in win,
    "Device Memory": "deviceMemory" in nav,
    "Touch Gestures": "ontouchstart" in win || "onpointerdown" in win,
    "Idle Detection": "IdleDetector" in win,
    "Presentation Features": "presentation" in nav || "PresentationRequest" in win,
    "Fullscreen": "requestFullscreen" in doc.documentElement || "mozRequestFullScreen" in doc.documentElement || "webkitRequestFullscreen" in doc.documentElement || "msRequestFullscreen" in doc.documentElement,
    "Screen Orientation": "orientation" in scr || "mozOrientation" in scr || "msOrientation" in scr,
    "Orientation Lock": "orientation" in scr || "mozOrientation" in scr || "msOrientation" in scr,
    "Wake lock": "keepAwake" in scr || "wakeLock" in nav,
    "Device Position": "DeviceOrientationEvent" in win || "AbsoluteOrientationSensor" in win || "RelativeOrientationSensor" in win,
    "Device Motion": "DeviceMotionEvent" in win || "LinearAccelerationSensor" in win && "Gyroscope" in win,
    "Web Share": "share" in nav,
    "File Share": "share" in nav && "canShare" in nav,
    "Battery Status": "getBattery" in nav || "battery" in nav,
    "Vibrate": "vibrate" in nav,
    "USB": "usb" in nav || nav.usb,
    "Serial Port": "serial" in nav || nav.serial,
    "Ambient Light": "ondevicelight" in win || "AmbientLightSensor" in win,
    "Bluetooth": "bluetooth" in nav,
    "Midi devices": "requestMIDIAccess" in nav,
    "Proximity Sensors": "ondeviceproximity" in win || "onuserproximity" in win || "ProximitySensor" in win,
    "GravitySensor": "GravitySensor" in win,
    "Magnetometer": "Magnetometer" in win,
    "Gyroscope": "Gyroscope" in win,
    "Accelerometer": "Accelerometer" in win,
    "Linear Acceleration Sensor": "LinearAccelerationSensor" in win,
    "Media Capabilities": "mediaCapabilities" in nav,
    "mediaDevices": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Camera": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Media Session": "mediaSession" in nav,
    "Image Capture": "ImageCapture" in win || "ImageCapture" in nav,
    "Recording Media": "MediaRecorder" in win || "MediaRecorder" in nav,
    "Real-Time Communication webrtc": "RTCPeerConnection" in win || "webkitRTCPeerConnection" in win,
    "Audio": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Audio Capture": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Video": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Video Capture": "mediaDevices" in nav || "getUserMedia" in nav || "webkitGetUserMedia" in nav || "mozGetUserMedia" in nav || "msGetUserMedia" in nav,
    "Augmented Reality": "getVRDisplays" in nav || "xr" in nav,
    "Virtual Reality": "getVRDisplays" in nav || "xr" in nav,
    "Speech Recognition": "SpeechRecognition" in win || "webkitSpeechRecognition" in win,
    "Barcode scanner": "BarcodeDetector" in win,
    "Facial recognition": "FaceDetector" in win,
    "Text Detection": "TextDetector" in win,
    "Payment Request": "PaymentRequest" in win,
    "Payment Handler": "paymentManager" in registration,
    "Credential Management": "credentials" in nav &&
        "preventSilentAccess" in nav.credentials &&
        ("PasswordCredential" in win || "FederatedCredential" in win)
};
};

function setCompatibilityArray(browserFeatures) {
for (const feature in browserFeatures) {
    if (!browserFeatures.hasOwnProperty(feature)) {
        continue;
    }
    var nf = feature.toString().replace(/[^A-Za-z0-9]/g, '').toLowerCase();
    var val = browserFeatures[feature] ? "1" : "0";
    testArr[nf] = {
        'name': '' + feature + '',
        'value': val
    };
}
_set('browserFeature', testArr, 1);
 //here use console.log(testArr); to get the variable names for your requirements     array
};

function getFeatures() {
testArr = _get('browserFeature', 0, 1);
if (testArr == 0) {
    if ("serviceWorker" in navigator) {
        testArr = {};
        return navigator.serviceWorker.register("service-worker.js")
            .then((registration) => {
                const browserFeatures = detectFeatures(registration);
                setCompatibilityArray(browserFeatures);
            });
    }
}
}

how to use it:
on document.load || .ready place this function, getFeatures();
the _get() and _set() functions gets and sets a local storage variable of the array testArr which contains all the features of the browser and whether the feature is true or false.
in the testArr the key name is the feature names that are joined and in lowercase, you can create your own "required features" array using these key names.
like so:
 var canwork = true;
 var permissionReqArr = ['one','two','three','four','five'];
 // permissionReqArr contains the variables requirements for app to work,
 you can get this from the getFeatures function by using console.log() on the result testArr.

then:
for(var i = 0; i < permissionReqArr.length; i++){
 var check = testArr[permissionReqArr[i]];
 if(check == false || check == 0){
 canwork = false;
 }
}

if(canwork == false){
alert('your browser is not compatible, you will not be able to download/install this app');
}

if this helps you in anyway please vote me up, i need the points..
notes:
if you don't want to actually install the service-worker.js, then use this code inside your service-worker.js file:
 self.addEventListener("install",()=>{}), self.addEventListener("activate", ()=>self.clients.claim());

//Will not install anything in the browser only return the registration event to capture other features of the browser
also this Function will only call the service-worker if the features localstorage item is not set.. if you do have a service worker, then make sure to remove this block from the above..
the _set and _get functions return zero, if the localstorage item is not set, you can make your own function for this..


Data Factory v2 - connecting using REST

Question: The aim is to connect to a public REST api using ADF. It's my first stab at sending requests to a REST api in ADF. It is the Companies House ('CH') governement website's  API in England.
I have created an account and obtained a key.  Apparently, it is basic authentication and the user name is the API key and password will be ignored (CH note on authentication)
I want to explore the contents of the 'Search all' API (CH note on Search All) and want to copy the results to Blob Storage.
I therefore set the linked service to use REST as below, the obfuscated User Name is the key I obtained from CH, the password is jsut the key repeated as their documentation states they ignore the password:
[
I then have added a REST dataset referencing this linked service:

And the testing of the connection works fine.
Problems then arise in the copy data task, I am getting an error when previewing and also when I attempt a copy to blob of 'Invalid Authorization Header':

I'd be grateful for pointers on where I'm going wrong.
Answer: I can't reproduce your Auth error but i notice that you want to add some parameters with your GET request in the Request Body.

I think you need to add parameters in relativeUrl property:

A relative URL to the resource that contains the data. When this
  property isn't specified, only the URL that's specified in the linked
  service definition is used. The HTTP connector copies data from the
  combined URL: [URL specified in linked service]/[relative URL
  specified in dataset].

Also i suggest you checking the correct REST API format of Search Api you are using.There is no other special features in the ADF REST connector. Just make sure the GET request works locally and duplicate it.

Data Factory v2 - connecting using REST


refrigerator stops working

Question: I have a refrigerator in a rental that stopped working. (Kenmore Coldspot model# 106.74264400)  It is less than 5 years old.
On initial inspection it was not cooling, the thermostat was set to five, and the interior light was working; nothing seemed amiss.  I cleaned the coils although they were not terribly dirty.  I turned the temp knob to zero and when I reset it to 5 it went back to cooling normally.
Since then it occasionally will stop working.  If the temp is turned to off and then reset to five, it will return to cooling, sometimes for several weeks.
What could be causing this?
Comment: By not working you mean it stops cooling permanently?  Since it starts back up when you adjust the thermostat, I'd suspect that thing...
Answer: One common cause (since you don't give much detail on how, exactly, it stops working) would be an unreliable or broken defrost circuit, and ice building up in air passages, blocking fans, and thus causing the fridge to not cool because cold air can't get from the coils to the fridge.
Another, or possibly related cause would be slightly low refrigerant (a leak that has not progressed to the point of completely not working) making the coils too cold, causing faster than usual ice build up, which the defrost is not compensating for.
Comment: A failing defrost timer is a common one for sure.
Comment: Thanks for the  possibilites.

refrigerator stops working


iPhone keyboard in UIWebView, how to change the language of next/previous and done buttons

Question: UIWebView's keyboard is pretty cool with its next/previous and done buttons. However, I was not able to find and change the button titles. The titles are always in english no matter in which language the system is running.
Comment: Mine change correctly when I switch the phone's language.
Comment: Sorry, I mean UIWebView not safari.
Comment: Unless you have your own keyboard designed by you which overrides stock one, your unable to change stock keyboard language (it's taken from iOS language set via Preferences > General > International).
Answer: I have been looking for the answer to this for a while for my PhoneGap based application, and at last I found the answer here: UIWebview Localization.
The clue is to set 'CFBundleAllowMixedLocalizations' to 'Yes' in your info.plist. That really made my day :)
Answer: You can set your own view on top of the keyboard. It is really easy after 3.2 and I have some sample code in this answer. That means you can use your own buttons and even set localized text there.
EDIT: That was a bad answer :) Sorry, I didn't see the 'mobile-safari' tag. But in my case, I also get localized versions of the keyboard previous/next buttons.
Answer: Unless you have your own keyboard designed by you which overrides stock one, you can't do that.
Stock keyboard's language is taken from iOS language setting (via Preferences > General > International).
Comment: I don't think this is true. The first thing I did was change the device language, but regardless of the region/language settings, the buttons always come up in English. I've been fighting with this on iOS 5.1, 6, and 7. Still don't have the solution...
Comment: Havard's answer and link are correct.l Changing the device language only works if you have set the correct flag in the Info.plist.


Planting and farming blinkroot

Question: I found some Blinkroot Seeds and now want to plant them to get the whole potion brewing going. What do I have to keep in mind when planting those?
I only found Blinkroot underground, so do I also have to plant them underground? Do they have any other requirements?
Comment: Related: http://gaming.stackexchange.com/questions/25288/what-makes-plants-bloom
Answer: Strangely enough, there is nothing to keep in mind.
They will grow anywhere at any level, provided that you plant them in a Clay Pot.
They also grow on plain dirt and mud. However, this is undesirable when making a Blinkroot farm, because fully grown Blinkroots switch on and off at random intervals. They can be harvested all the same, but "inactive" Blinkroots will not drop any seeds. Thus, planting them in Clay Pots is preferable, because they allow for selective harvesting.
Comment: Must you replant the pot after each blinkroot is harvested, or does it self-perpetuate?
Comment: @RavenDreamer They have to be replanted after each harvest. If they're blooming, you're guaranteed at least one seed per drop, though. Blinkroots in particular bloom when they're mature and they feel like it. Other herbs have more specific requirements.

Planting and farming blinkroot


Automate Create tables procedure using Dynamic SQL using cursor or loop - PLSQL

Question: Syntax: PL SQL
IDE: PL/SQL Developer
I'm attempting to generate 4 tables for each region using a series of Region codes.
I understand that it may be more efficient to generate one table with all regions included and truncate and replace this table however based on the structure needed for use I am not allowed to this.
The 4 regions come from a Specific table
SELECT DISTINCT REGION
FROM REGION_TABLE
;

What is the best method to generate this series of tables dynamically?
I've attempted to use a cursor and a loop but I am unsure of the method to integrate this cursor into the following Procedure.
DECLARE
CURSOR C_REGION IS
       SELECT DISTINCT REGION FROM REGION_TABLE ;
BEGIN
     FOR L_IDX IN C_REGION
     LOOP
     DBMS_OUTPUT.PUTLINE(L_IDX.C_REGION);
     END LOOP;
END;

Using the cursor values above, how do I go about inserting these values into not only the table name used in the Create Table portion of the Sql statement but as a parameter in the where clause
-- 4 REGIONS  - NORTH SOUTH EAST WEST,

CREATE OR REPLACE PROCEDURE SALES_ORDER_TBL_PROC
          (
          REGION IN VARCHAR2
          , RETURNCODE OUT NUMBER
          , ERROR_MESSAGE OUT VARCHAR2
          )
            IS
  TABLE_NAME VARCHAR2(30);
  SQL_STR VARCHAR2;
  REGION_VAR VARCHAR;
BEGIN
  TABLE_NAME := 'SALES_COUNT_'||REGION_VAR;
  SQL_STR := 'CREATE TABLE '||TABLE_NAME||
             ' AS
               (
               SELECT
                      REGION
                          , COUNT(DISTINCT MEMBER_ID) AS NUM_MBR
                      FROM INCREMENTAL_SALES_TBL
                      WHERE 1=1
                          AND REGION = '||REGION_VAR||
                          'GROUP BY REGION)'
               ;

 EXECUTE IMMEDIATE SQL_STR ;

         RETURNCODE := 0;

 EXCEPTION WHEN OTHERS THEN

         RETURNCODE := SQLCODE;

         ERROR_MESSAGE :='ERR:Creating/Altering table '||TABLE_NAME ||'-'||SQLERRM;
END;
/

BEGIN
     SALES_ORDER_TBL_PROC;
END;

Comment: creating tables seems like a one time job. why do you need a procedure for it?
Comment: better truncate and load the data over
Comment: These are reporting tables.  - company procedure simply needs to them to be rebuilt on the fly.
Comment: Understood - but there must be 4 unique tables, per the requirements given.
Answer: How about putting the DDL in a for loop?  I haven't tested the code below but it should at least put you on a path toward your goal, hopefully.
FOR rec IN (SELECT DISTINCT REGION FROM REGION_TABLE) LOOP
  EXECUTE IMMEDIATE
    'CREATE TABLE SALES_COUNT_' || UPPER(rec.region) || ' AS (
       SELECT REGION,
              COUNT(DISTINCT MEMBER_ID) AS NUM_MBR
         FROM INCREMENTAL_SALES_TBL
        WHERE REGION = ''' || rec.region || '''
        GROUP BY REGION)';
END LOOP;

I can't remember what the restrictions are when it comes to concatenation with EXECUTE IMMEDIATE, but if it's not working then it's possible to use bind variables and the USING clause.
Comment: This process worked very well and executed with a few tweeks.
Comment: This process worked very well and executed with ONE tweek. 1. The where clause should be WHERE REGION = '''|| REC.REGION|||''' Thank You
Comment: @BGDev ah, that gets me almost every time.  Glad you got it sorted out!  Thanks for pointing that out, I'll fix it in the answer.


Formik and Semanic UI React. Delay on typing, unnecessary validation

Question: Here is a simple example of my dynamic form.
<Form.Group widths='equal'>
                    <Form.Input onChange={props.handleChange} fluid name={`${type}.${participant.number}.firstName`}
                                label={FIRST_NAME}
                                placeholder={FIRST_NAME_MODEL_DESCR}/>
                    <Form.Input onChange={props.handleChange} fluid label={LAST_NAME}
                                name={`${type}.${participant.number}.lastName`}
                                placeholder={LAST_NAME_MODEL_DESCR}/>
       </Form.Group>

in the Fromik itself i have simple console.log
    validate={values => {
        console.log(values);
    }}

So on every time when i'm typing into field, on every key press i'm getting log results from validation (which i don't want) and it has micro delay, on every key press down.
Comment: Well, you put in input fields onChange function. That is the reason why is it happening. What would you like to achieve?
Comment: how else could i get the value of input field? this "handleChange" is a Formik function. I would like to have all my values validated on submit only.
Answer: Pass validateOnChange (and validateOnBlur if you want to disable that too) with a value of false to the Formik component (https://jaredpalmer.com/formik/docs/api/formik#validateonchange-boolean)
Comment: Yeah, it does because Formik holds the state of your form and the rest of your form is a child, and when a parent component re-renders, so does all of it's children unless shouldComponentUpdate returns false somewhere in the component tree. So if you need to prevent part of your form from re-rendering (usually isn't necessary unless you have a larger form), split your form fields out into separate components and use PureComponent to prevent components whose props don't change from re-rendering.
Comment: Still the whole form is rerendering when i'm typing into field. For change i'm using handleChange.
Comment: Hi @TLadd, can you tell me or show an example of how to do that? I'm having the same problem with slowness because of re-renders using `` -> `` -> ``
Comment: @GuilhermeMoretto The Formik docs detail how to deal with performance problems using FastField https://formik.org/docs/api/fastfield. I'd give this a read.
Answer: If you would like to validate your fields on submit only, and since you are using Semantic-UI-React's Form component, I suggest using onSubmit handler function that Semantic is offering.
<Form onSubmit={this.handleSubmit}>
  <Form.Group>
    <Form.Input placeholder='Name' name='name' value={name} onChange={this.handleChange} />
    <Form.Input
      placeholder='Email'
      name='email'
      value={email}
      onChange={this.handleChange}
    />
    <Form.Button content='Submit' />
  </Form.Group>
</Form>

With this to set your input value to the state handleChange = (e, { name, value }) => this.setState({ [name]: value })
And you can use this function to handle with formic your data validation
  handleSubmit = () => {
    const { name, email } = this.state

    // here you can use formic to validate name and email
  }


If $a$ and $b$ are constants, calculate the definite integral

Question: $$\int_{-\infty}^{+\infty} F(x-b) f(x-a) dx$$
$$f(x) = \exp(-x-e^{-x}), \qquad x \in (-\infty, +\infty)$$
$$F(x) = \int_{-\infty}^x f(t) dt$$
I calculated already the integral of $F(x)$, which is $\exp(-e^{-x})$, but I am stuck on the other one, I have no idea how to calculate the integral of $F(x-a)f(x-b)$.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: $$\int_{-\infty}^{\infty}F(a-b)f(x-a)dx=\int_{-\infty}^{\infty}e^{-e^{-(x-b)}} e^{-(x-a)} e^{-e^{-(x-a)}}  dx=$$
$\Rightarrow e^{a} \int_{-\infty}^{\infty} e^{-e^{-x}({e^{b}+e^{a}})} e^{-x}   dx$
Now Let,  $-e^{-x}=t,  \rightarrow e^{-x} dx =dt$
$\Rightarrow e^{a} \int_{-\infty}^{0} e^{t{(e^{a}+e^{b}})}   dt~~$
$\Rightarrow \frac{e^a}{e^{a}+e^{b}}.$


Wiring from Oven to Switch

Question:
At the moment under the oven switch the cable is plastered over (without capping) till it reaches under the counter; there it pops out of the raw plaster and is draped across the back of the units to the double-oven housing where its just wired into the back of the oven.
My sparky suggested channeling out the wall (light blue line) down and across, then capping it. But I was wondering if it was better, or if theres any reason not to channel straight down to the floor boards, then tac the cable to the joist across the width of  the kitchen before coming up (channeling again) to the cooker connection point (as in the purple line).
The blue line would be 70cm high; total length of cable travel 150cm
And this is in the UK.
Comment: What is the actual question you're asking? Does it relate to electricals or laying wire across a wall?
Comment: @alt It was relating to the path the wiring could/should take.
Answer: In some places it is illegal to run hidden power cables horizontally across walls unless they are within a specific short distance from floor or ceiling.
For example, in the UK I believe all power cables to/from a mid-wall switch must run vertically to or until near the floor/ceiling.
So, the answer may depend where you live.

Reference: IET cables in walls
Comment: Updated with lengths. The blue line would be 70cm high (from floor); total length of cable travel 150cm (horizontal). And UK based, the land of Part-P headaches and restricted zones
Comment: @Chris: See reference above. It's complicated but I think you need to route in the other direction, up across down.
Comment: http://www.ultimatehandyman.co.uk/WIRE%20IN%20JOISTS.jpg the safe zones "permitted routes" afaik relate to cables unprotected (no trunking/conduit) and near the surface. We had a plug socket added by an electrician for the hob ign which goes down and dog legs to the left. Exceeding max travel and having a huge channel the length of the wall is a worry. Joist seems less (bar floorboard removal)

Wiring from Oven to Switch