Notations regarding Random Variables.

Question: This is about notations used in the discussion of Random Variables in the book Schaum's Outline of Probability, Random Variables, and Random Processes by Hwei Hsu, Chapter-2, Page-38.

Let, we flip a coin thrice, and a random variable $X$ represents the number of heads.

Then,
a.   $S = \{TTT, HTT, THT, TTH, HHT, HTH, THH, HHH\}$.
 b.   $\zeta = TTT, HTT, THT, TTH, HHT, HTH, THH, HHH$.
 c.   $X(\zeta) = x = 0, 1, 2, 3$.
 d.   $X(\zeta_1) = X(\{TTT\}) = 0 = x_1$
 e.   $X(\zeta_2) = X(\{HTT\}) = 1 = x_2$
 f.   $X(\zeta_3) = X(\{THT\}) = 1 = x_2$
 g.   $X(\zeta_4) = X(\{TTH\}) = 1 = x_2$
 h.   $X(\zeta_5) = X(\{HHT\}) = 2 = x_3$
 i.   $X(\zeta_6) = X(\{HTH\}) = 2 = x_3$
 j.   $X(\zeta_7) = X(\{THH\}) = 2 = x_3$
 k.   $X(\zeta_8) = X(\{HHH\}) = 3 = x_4$
 l.   $(X=x) = \{TTT\}, \{HTT, THT, TTH\}, \{HHT, HTH, THH\}, \{HHH\}$.
 m.   $(X=0)=\{TTT\}$
 n.   $(X=1)=\{HTT, THT, TTH\}$
 o.   $(X=2)=\{HHT, HTH, THH\}$
 p.   $(X=3)=\{HHH\}$
 q.   $(X\le3) = \{TTT\}, \{HTT, THT, TTH\}, \{HHT, HTH, THH\}, \{HHH\}$.
.
Is any of these assumptions incorrect?
Note. kindly point out if there is any typo.
Comment: $X(\zeta)$ represents the number of heads in the event $\zeta$. Is that what your question is?
Answer: The random variable $X$ is a function $S \to \mathbb{R}$.
Thus,  $X(\zeta)$ is the image of $\zeta$ induced by $X$.
That is,
$$\begin{align}
X(\zeta)&=\{X(z): z \in \zeta\} \\
&= \{X(TTT), X(HTT), X(THT), X(TTH), X(HHT), X(HTH), X(THH), X(HHH)\} \\
&= \{0, 1, 2, 3\}\text{.}
\end{align}$$
Comment: Is this correct:  **c.**   $X(\zeta) = x = 0, 1, 2, 3$.  ?

Notations regarding Random Variables.


How to setup MTLTexture and MTLBuffers for Metal Performance Shaders Find Keypoints

Question: Problem
I'm trying out the performance shaders for the first time and encountered a runtime problem. The MTLTexture that MTKTextureLoader returns seems to be uncompatible with Metal Performance Shaders' MPSImageFindKeypoints encoder.
The only hint so far that I found is from @warrenm's sample code on MPS that specifies MTKTextureLoaderOptions just like I did. I did not find any other mentions in the docs.
Any help is highly appreciated.
Error
/BuildRoot/Library/Caches/com.apple.xbs/Sources/MetalImage/MetalImage-121.0.2/MPSImage/Filters/MPSKeypoint.mm:166: failed assertion `Source 0x282ce8fc0 texture type (80) is unsupported

where 0x282ce8fc0 is the MTLTexture from the texture loader.
As far as I could see there is no MTLTexture type 80, the enum ranges up to 8 or so (not hex).
Code
CGFloat w = CGImageGetWidth(_image);
CGFloat h = CGImageGetHeight(_image);
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> commandQueue = [device newCommandQueue];

NSDictionary* textureOptions = @{ MTKTextureLoaderOptionSRGB: [[NSNumber alloc] initWithBool:NO] };
id<MTLTexture> texture = [[[MTKTextureLoader alloc] initWithDevice:device] newTextureWithCGImage:_image
                                                                                options:textureOptions
                                                                                error:nil];
id<MTLBuffer> keypointDataBuffer;
id<MTLBuffer> keypointCountBuffer;

MTLRegion region = MTLRegionMake2D(0, 0, w, h);

id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
MPSImageKeypointRangeInfo rangeInfo = {100,0.5};
MPSImageFindKeypoints* imageFindKeypoints = [[MPSImageFindKeypoints alloc] initWithDevice:device
                                                                                info:&rangeInfo];
[imageFindKeypoints encodeToCommandBuffer:commandBuffer
                            sourceTexture:texture
                                  regions:&region
                          numberOfRegions:1
                      keypointCountBuffer:keypointCountBuffer
                keypointCountBufferOffset:0
                       keypointDataBuffer:keypointDataBuffer
                 keypointDataBufferOffset:0];

[commandBuffer commit];

NSLog(keypointCountBuffer);
NSLog(keypointDataBuffer);

Edit
After converting my image to the correct pixel format I am now initialising the buffers like so:
id<MTLBuffer> keypointDataBuffer = [device newBufferWithLength:maxKeypoints*(sizeof(MPSImageKeypointData)) options:MTLResourceOptionCPUCacheModeDefault];
id<MTLBuffer> keypointCountBuffer = [device newBufferWithLength:sizeof(int) options:MTLResourceOptionCPUCacheModeDefault];

There is no error anymore. But how can I reading the contents now?
((MPSImageKeypointData*)[keypointDataBuffer contents])[0].keypointCoordinate returns (0,0) for all indexes. Also I don't know how to read the keypointsCountBuffer. The buffer contents converted to an int value show a higher value than the defined maxKeypoints. I don't see where the docs say what kind of format the count buffer has.
Comment: Are you really not setting `keypointDataBuffer` or `keypointCountBuffer` before encoding the command? Maybe not relevant, but could break things internally such that the assertion is a "sympathetic" error and misleading. Also, those `NSLog()` calls can't work. They need a format string.
Comment: @KenThomases Yes currently I don't know any better than to assume that both buffers will be initialized by MPS upon calling encode or when committing the commandBuffer, since the docs don't specify how these buffers should be set and I would not know how large the buffer needs to be. I guess I could set the `keypointDataBuffer` to the maximum keypoints count that I define in the `rangeInfo` and try again. Indeed I was expecting maybe getting errors for those logs but I just did not look up how to log MTLBuffers yet.
Comment: I just saw that I overlooked that the docs state that `MPSImageFindKeypoints` needs a texture with `MTLPixelFormatR8Unorm`. So After correcting the images pixel format I indeed run into the error that keypointsDataBuffer may not be null
Comment: In (Objective-)C (as opposed to C++), a method can't modify a variable passed as an argument unless you pass its *address*. So, there was no chance that the method would create buffers and set your variables to point to them, given how they're passed.
Answer: Finally the code is running and just for completeness sake I thought I should post the whole code as an answer
code
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> commandQueue = [device newCommandQueue];

// init textures
NSDictionary* textureOptions = @{ MTKTextureLoaderOptionSRGB: [[NSNumber alloc] initWithBool:NO] };
id<MTLTexture> texture = [[[MTKTextureLoader alloc] initWithDevice:device] newTextureWithCGImage:_lopoImage
                                                                                options:textureOptions
                                                                                error:nil];
MTLTextureDescriptor *descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:(MTLPixelFormatR8Unorm) width:w height:h mipmapped:NO];
descriptor.usage = (MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite);
id<MTLTexture> unormTexture = [device newTextureWithDescriptor:descriptor];

// init arrays and buffers for keypoint finder
int maxKeypoints = w*h;
id<MTLBuffer> keypointDataBuffer = [device newBufferWithLength:sizeof(MPSImageKeypointData)*maxKeypoints options:MTLResourceOptionCPUCacheModeWriteCombined];
id<MTLBuffer> keypointCountBuffer = [device newBufferWithLength:sizeof(int) options:MTLResourceOptionCPUCacheModeWriteCombined];

MTLRegion region = MTLRegionMake2D(0, 0, w, h);

// init colorspace converter
CGColorSpaceRef srcColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
CGColorSpaceRef dstColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceLinearGray);

CGColorConversionInfoRef conversionInfo = CGColorConversionInfoCreate(srcColorSpace, dstColorSpace);
MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice:device
                                  srcAlpha:(MPSAlphaTypeAlphaIsOne)
                                 destAlpha:(MPSAlphaTypeNonPremultiplied)
                           backgroundColor:nil
                            conversionInfo:conversionInfo];

// init keypoint finder
MPSImageKeypointRangeInfo rangeInfo = {maxKeypoints,0.75};
MPSImageFindKeypoints* imageFindKeypoints = [[MPSImageFindKeypoints alloc] initWithDevice:device
                                                                                info:&rangeInfo];

// encode command buffer
id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
[conversion encodeToCommandBuffer:commandBuffer sourceTexture:texture destinationTexture:unormTexture];
[imageFindKeypoints encodeToCommandBuffer:commandBuffer
                            sourceTexture:unormTexture
                                  regions:&region
                          numberOfRegions:1
                      keypointCountBuffer:keypointCountBuffer
                keypointCountBufferOffset:0
                       keypointDataBuffer:keypointDataBuffer
                 keypointDataBufferOffset:0];

// run command buffer
[commandBuffer commit];
[commandBuffer waitUntilCompleted];

// read keypoints
int count = ((int*)[keypointCountBuffer contents])[0];
MPSImageKeypointData* keypointDataArray = ((MPSImageKeypointData*)[keypointDataBuffer contents]);
for (int i = 0 ; i<count;i++) {
    simd_ushort2 coordinate = keypointDataArray[i].keypointCoordinate;
    NSLog(@"color:%f | at:(%u,%u)", keypointDataArray[i].keypointColorValue, coordinate[0], coordinate[1] );
}

I guess there should be a more clever way to allocate the keypoint buffers with [device newBufferWithBytesNoCopy] so then you would not need to copy the contents back into your allocated arrays. It just didn't figure out to correctly align the buffer.
Also I should mention that I guess usually you will have a grayscale texture after any kind of feature detection so that the image converting part will not be necessary.


How do I run objcgen directly to do .NET Embedding on MacOS

Question: I followed the instructions  at Installing .NET Embedding and...

I installed Visual Studio 2019 on my Mac 10.14.6
I created a Xamarin.ios class lib project
I installed Nuget Embeddinator-4000
I added a hello world function: void main(){ Console.WriteLine("hello world");}...
I built without problem.
The next instruction says to.....

<code> Running manually
    Now that the NuGet is installed, you can run the tooling by hand.
    Open a Terminal (macOS) or Command Prompt (Windows)
    Change directory to your solution root
    The tooling is installed in:
    ./packages/Embeddinator-4000.[VERSION]/tools/objcgen (Objective-C)
    ./packages/Embeddinator-4000.[VERSION]/tools/Embeddinator-4000.exe
    On macOS, objcgen can be run directly.
</code>

...But there is no ./packages/ directory  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<code>> Last login: Fri Mar  6 10:05:48 on ttys002
> DOUGs-MacBook-Pro:Embedding_2020-03-06 dbell$ ls -l total 24
> -rw-r--r--  1 dbell  staff  2193 Mar  6 09:02 Embedding_2020-03-06.csproj
> -rw-r--r--  1 dbell  staff   827 Mar  6 08:58 Embedding_2020-03-06.sln
> -rw-r--r--  1 dbell  staff   249 Mar  6 09:03 HelloWorld.cs drwxr-xr-x  3 dbell  staff    96 Mar  6 08:58 Properties drwxr-xr-x  3 dbell
> staff    96 Mar  6 08:58 bin drwxr-xr-x  8 dbell  staff   256 Mar  6
> 09:03 obj DOUGs-MacBook-Pro:Embedding_2020-03-06 dbell$ ls ./packages
> ls: ./packages: No such file or directory    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
> DOUGs-MacBook-Pro:Embedding_2020-03-06 dbell$
</code>
Comment: check in your bin or obj folders
Answer: Ah, hah!  The objcgen tools need to first be built.  I found instructions how at Github > Embeddinator-4000 > README.md > "Building".
Summary -- installation of .NET to Objective-C converter...
<code>1.  Clone github > Embeddinator-4000
git clone https://github.com/mono/Embeddinator-4000.git
2.  cd into the cloned dir
3.  Install other stuff:
git submodule update --recursive --init
4.  Build the .NET to Objective-C converter:
cd objcgen
make
5.  Build the 'wrapper' (ie. command access) to objcgen (took 10-15 minutes for me):
make nuget
6.  Generate Objective-C from your .NET C# class lib
7.  <somewhere in the bowels of your Mac>/Embeddinator-4000/objcgen/_build/objcgen     <elsewhere in the bowels of your Mac>/hello-from-csharp/hello-from-csharp/bin/Debug/hello_from_csharp.dll --target=framework --platform=iOS --outdir=output -c --debug
</code>
NOTE:  hello-from-csharp is from MICROSOFT DOC .NET EMBEDDING HELLO WORLD


Android - how to escape @ symbol in setText() method

Question: I am trying to set text for an EditText field.
String someText = "email@example.com"
EditText et = (EditText) findViewById(R.id.someEditTextField);
et.setText(someText);

I have tried someText.replace("@", "\' @"); but it does not work.
I get the following exception java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Answer: This has nothing to do with escaping an @ sign. As the error points out to you, et is null.
Answer: As @CommonsWare states, this is your problem:
EditText et = (EditText) findViewById(R.id.someEditTextField);

your object et is null. You probably need to inflate/reference the layout it is in first.
An "@" is acceptable.


Minecraft Five Nights at Freddy's door/jumpscare system

Question: I got a tip to break up my questions into parts so here it goes.
Background Information

I have created a "door" that is concrete powder and is pushed up and down by redstone, pistons, and a lever.

how i am making the animatronics move is a scoreboard and a command block scenes when it reaches a certain score and when it does they teleport using
/tp @e[type=armor_stand, name=Foxy] 8 11 9 facing 8 11 8 this is right outside the door.

So what i am asking is, how would I use commands blocks and redstone so that when the animatronic is outside the door, it sees if the door is closed, and if not, jump scare? How would i create two paths for it to follow?
Answer: First at the jumpscare block (the block where the animatronic is considered ready to jumscare) place a dirt block below this block. This is important.
Name the armor stand "animatronic"
Make the door an iron door, forcing the player to control it with a lever. YOU WANT THIS. This is the source of the entire jump scare code. This also means the wall that the lever is on must be three blocks thick so redstone can go through it. The level should control the door(the door is simply decoration at this point). Make a redstone path inside the wall that goes up. This is best with slabs going like this to the roof of your build:

Once that is we will take out our command blocks. First create a repeating command block. DO NOT CONNECT THIS TO THE REDSTONE. The properties should be: Unconditional, always active, 0 tick delay. Then enter this code:
/execute @e [name= animatronic] ~ ~ ~ /testforblock ~ ~-2 ~ dirt
This command checks if the animatronic is at the jumpscare position.
Then place a conditional chain command block in front of it with the properties always active, conditional, 0 tick delay with no code.
Dont remove the command block because it doesn't have a code. It is simply there to send a signal when the animatronic is on the jumpscare block.
Now feed a comparator out of it. Now place two redstone dust away from the comparator and place another comparator. This is where your redstone from the lever takes place. Connect it to the side of the second comparator(place levers if needed). MAKE SURE THE SIGNAL STRENGTH IS AT 14 WHEN IT CONNECTS OR IT WILL NOT WORK. This will tell the game if the door is closed or not. Now place repeating command block with 0 tick delay, needs redstone, and unconditional and the following code:
/tp @p ~ ~ ~ facing armor_stand [name = animatronic]
This makes the player face the monster as it jumpscares you.
Place a chain command block with the properties unconditional, always active, 25 tick delay. This is the jumpscare command. You choose what to do with it.
Finally place a final chain command block in front of the other one with the properties of unconditional, always active, tick delay varies on how long you want the jumpscare to last. With the code:
/kill @p
That's it!


How do you get the string of a variable name in javascript?

Question: I have a variable as such:
 var foo = ["cool", "cool"];

How do I get the variable name, foo, as a string? In other words, given foo, how do I get "foo"? I want to use it in the following context where "foo" is used in getElementById(...):
  document.getElementById("foo").innerHTML = document.getElementById("foo").innerHTML + "";

Thanks!
Comment: You can't do that (unless you're in the global scope and want to iterate through the properties on `window`). You might want to consider using an _Object_ instead; i.e. `var o = {foo: ["cool", "cool"]};` Now say you have `var x = o.foo;` you can iterate over `o` to find `key` using `o[key] === x`
Comment: Can you elaborate on the code you want to write? It's not clear how the above code fragment is called or what you expect to happen. If we understand what you are trying to do, maybe we can come up with a solution that doesn't involve knowing the variable name. For example, why not just pass the string "foo" to the function? The value of `foo` is never used.
Answer: If it's a global variable, you get it as global object property: window in browsers and global in NodeJS. Otherwise, you don't.
Answer: You're looking at this the wrong way round - to answer this question directly

given foo, how do I get "foo"?

Well, the answer is... type "foo" in your code.
You know you want the string representation of the foo variable name when you write your code, so there's no scenario where the string value you want would be anything other than "foo", right?
It's true that you can reference a property foo, for example of the window object, using window["foo"] but that's the other way round too - you have to know it's foo you want, and deliberately use "foo" to get at it. So there's an example - you know what string to use, "foo", at compile time - it couldn't possibly be anything else.


What is the type of alert called when it doesn't require user interaction? And when should I use it?

Question: I'm speaking of alerts that don't require the users direct attention, more of a "oh, by the way, this actions just happened". Not much unlike gmail's "you action has been undone" or "Your message has sent".

I would hate to have to click "OK" every single time that that I send an email in gmail, but it's good to know that the action completed without error.
Is there a standard name for these types of alerts and are there rules as to when I should use them?
Comment: These are often called "flash messages". There are a few old threads here about them.
Answer: In Android, there is a "Toast" that is a message that is displayed briefly and then automatically disappears.
Comment: Actually toasts don't always disappear automatically.  Google's Material Design spec allows for toasts which have DISMISS, OK-RETRY or other buttons which can dismiss the toast.
Comment: Yes those are valid option for a toast message. By default though Toast automatically disappears. http://developer.android.com/guide/topics/ui/notifiers/toasts.html This term is also by Microsoft and Adobe. http://ux.stackexchange.com/questions/11998/what-is-a-toast-notification The other term for this is a "pop-up notification"
Answer: "Notifications" is what you're talking about. As for rules, it's basically the scenario you outlined: use notifications when you just want to tell the user about something and no action is required on his or her part. A separate but related thing are "push notifications" on mobile devices (typically showing up on the phone's message bar).
Comment: We use the same classifications. I'd be interested to hear if there are other terms.
Answer: I think this is platform dependent. Different platforms have their own ways to name those. I find the names given by Apple for Mac OSX more intuitive.
Banner Appear for a short period of time and then disappear without interrupting what user is doing.
Alert Requires user's action and are important announcements that appear similar to banners
I think notification is too broad term that can contain both banner and alert and even badge.
Find more info here https://support.apple.com/en-gb/HT204079


entry door lock replacement

Question: My keys might have been compromised.
My options are :
1. Buy a Kwikset rekeying set and rekey all the locks (something I've never done before but there are enough Youtube videos that I can figure it out)
2. Replace all the locks with the Kwikset Smartkey locks and deadlocks so that in the future rekeying will be a 5 minute exercise.
Any thoughts on pros/cons of each approach?
Thanks
V
Comment: If you think you'll need to re-key regularly, then smartkey. Elseways, do the re-key yourself just the once. (Parenthetically, I've heard a rumor about smartkey locks forgetting their coding and locking you out... I don't have any statistical basis on which to judge this claim, but it might be something you want to research.)
Answer: If this is something you will only need to do one time, swap out the latchset. The chance of dropping the pins are high the first time around, but with care, it can be done. I know this from experience. The new latchset gives new longevity as well.
If this will be a recurring thing get the keying kit, I see them online and you can pick them up for as little as the cost of a new latchset, for the smaller kits. There are really cheap ones too, but I know nothing of what they have the capability of doing other than rekeying one knob.
I have no faith in the smartkey setup, but I am a purist when it comes to locks. I do not claim to know about smartkeys, but if it is a matter of putting in one key, installing a specific tool, and then put in the new key and remove the tool and it changes the lock, sounds like somebody with the original and a new key, and the same special tool can do the same.
Comment: You're correct about how the smartkey works: insert original key, insert pick-shaped tool (not special at all), insert new key, and you're done.
Comment: Thank you. After reading some more reports on the vulnerability of the Kwikset Smartkey locks (see [link](https://www.youtube.com/watch?v=sR-h64WwfW8) ) I believe buying the rekeying kit and rekey the locks is a safer option.

entry door lock replacement


Recursive query in SQL Server 2008

Question: I have this table
MyTable
rowNew  rowOld

1 ------- 2

2 ------- 3

3 ------- 4

4 ------- 5

7 ------- 8

8 ------- 9

I want to select query like this:
rowNew  rowOld

1 ------- 2

2 ------- 3

3 ------- 4

4 ------- 5

i wrote this with cte
with cte(rowNew, rowOld)
as
(
select rowNew, rowOld from MyTable
union all
select rowNew, rowOld from MyTable
inner join cte on MyTable.rowOld = cte.rowNew
)
select rowNew, rowOld from cte
where cte.rowNew = 1

and I got this records:
rowNew  rowOld

1 ------- 2

1 ------- 2

1 ------- 2

1 ------- 2

what is he problem?
Comment: How is your table different from your output? According to your setuo you can run a simple SELECT
Comment: This is some sort of hierarchical relationship, right?
Answer: You put your where condition in the wrong spot - it should be in the anchor query in the CTE definition to limit your starting point.
Also, you have join condition the other way round if you want to define parent-child relationship.
It all should be:
with cte(rowNew, rowOld)
as
(
select rowNew, rowOld from MyTable
where rowNew = 1
union all
select MyTable.rowNew, MyTable.rowOld from MyTable
inner join cte on MyTable.rowNew = cte.rowOld
)
select rowNew, rowOld from cte

SQL Fiddle demo

Recursive query in SQL Server 2008


What does the tree mean when generating a world?

Question: When you generate a new world in Terraria (in game not through the console) an icon of a tree is shown. The same icon will be shown when selecting the world from the list:

What are all the different possibilities and what do they mean?
Answer: The tree indicates what is on the world.
You can have either Purple/Green leaves which means that the world will have Corruption, or you can have Red/Green leaves which means that the world will have Crimson.
Also after defeating the Wall of Flesh (and entering hard mode) a yellow streak will appear on the tree indicating that the world has hallow in it.
In the following image, the first world has corruption and hallow, the second is a corruption world pre-hardmode, and the third image is a crimson world pre hardmode.


Can't install Ubuntu from USB on Intel Mac OSX 10.4

Question: I am trying to install Ubuntu on Intel Mac Osx 10.4. I followed all the instructions provided on Ubuntu forums. I also installed refit on my mac.
But after I restart the computer and go into the refit menu, I just see boot legacy OS options, and do not see any option for booting from the USB drive I created.
I am reading here that it the USB needs grub2 and so on but if there is anything extra needed it should be part of the clear instruction process. I have spent two frustrating days trying to install Ubuntu, and it certainly is not motivating.
Comment: Does this answer your question? [How to install Linux on old Mac X 10.4](https://askubuntu.com/questions/1206403/how-to-install-linux-on-old-mac-x-10-4)
Answer: I also have a Mac running Mavericks and I installed Ubuntu on it without using refit. Make sure the USB you are using is a bootable USB. I used a bootable DVD to do my installation, just because its much easier to create a bootable DVD using disk utility. Here are the steps I used: (This method worked for me, I am currently using Ubuntu to answer this question and do programming on it)
<code>   1. Use disk utility to make a free disk space partition of how much ever space you
      want to provide for your Ubuntu.
   2. Once you make the partition, you want to insert the DVD or USB into the macbook
      and restart your computer.
   3. On startup, hold down the 'alt' button on your macbook to get to the boot menu.
   4. Choose the boot DVD or USB and it should take you to the installation process.
   5. Once you go through the pick you language step, you should get an option
      asking if you want to install Ubuntu along side mac OS, remove your current OS
      and install Ubuntu, or custom.
   6. Choose whichever you want, whether you want to run it alongside or just have
      Ubuntu and remove Mac OS completely. That's your choice.
   7. From there just follow the steps and you should be good, it will update and
      when it restarts you will see the menu to boot from Ubuntu, or if you chose to
      run alongside mac, to boot from mac. (Quick Tip: If you choose to boot mac,
      don't choose mac from the boot menu whenever your laptop turns on. Just hit
      'esc' and type 'exit' and hit 'enter', that should boot in Mac OS then. If you want to boot in
      Ubuntu just leave it alone and it will automatically boot into Ubuntu.)
</code>
* Do remember to BACK UP YOUR MACBOOK before trying to install Ubuntu on your Mac since it is very tricky and kind of risky. If something goes wrong you can always boot back into Mac and install Mavericks again. Shouldn't lose anything but its always best to Backup! Remember it is TRICKY and RISKY so if you try this... Pay attention to what you do and try at your own risk.*
Comment: I have a old Mac Osx 10.4 Tiger. without working DVD drive.
Comment: does OSx Tiger have bootcamp? If it does, I believe the older boot camp versions should allow you to install Ubuntu
Comment: No bootcamp came with 10.5. I am on an older version. 10.4
Comment: oh... well in that case I will try to see what I can find out for you, but if you want upgrade from tiger and it will get much easier.


Support to read images via OPC UA with eclipse milo

Question: I just found in the OPCUA specification that images are supported (BMP, GIF, JPG and PNG) (see link). I also went through the org.eclipse.milo.opcua.stack.core.Identifiers and I see that types exist to handle those image formats:
    public static final NodeId ImageBMP = init(2000);
    public static final NodeId ImageGIF = init(2001);
    public static final NodeId ImageJPG = init(2002);
    public static final NodeId ImagePNG = init(2003);

The question is, has milo currently support for reading those image formats via OPCUA? Any example of how to do it?
Thanks!
Answer: You just read the Value attribute like any other VariableNode.
The result will be a ByteString. Those NodeIds you found are the ids of alias/simple DataTypes that inherit from ByteString and serve as a hint to what the contents of the ByteString will be.
It's up to you to turn the bytes into an image after that - it doesn't have anything to do with OPC UA or Milo at that point. You'll probably want to look at the ImageIO API.


Python Parallel Scraping + Dump to JSON

Question: Looking for opinions on the following skeleton code. I will be using a large input list for some web scraping and would like to parallelize the function along with writing the output to a json file in chunks in case the process fails I don't lose the work. The code produces the output I want, function f will be the scraper and the print(results) will be the output to the json file. Wondering if there is a more efficient method:
<code>import multiprocessing as mp
import os

def f(x):
    print('Doing: ' + str(x) + ' with process id:'+ str(os.getpid()) + '\n')
    return(x*x)

def main():
    id_list = range(1000)
    chunksize = 10

    lock = mp.Lock()

    for i in range(0, len(id_list), chunksize):
        chunk = id_list[i : i + chunksize]

        p = mp.Pool(12)
        results = p.map(f, chunk)

        for j in range(len(results)):
            lock.acquire()
            try:
                print('The results is: ' + str(results[j]) + '\n')
            finally:
                lock.release()
        p.close()

if __name__ == "__main__":
    main()
    print("Done")
</code>
Answer: Each process could write their own output into a separate file, and you can deal with combining them later.
That way you don't have to deal with locks or possible writing concurrency issues or whatever in this code at all.

Python Parallel Scraping + Dump to JSON


How can you dynamically allocate a pointer in the form int (*p)[n] in C?

Question: Suppose I get input from somewhere and store it in a variable. Pretend the variable is Cols.
I want to make an array in the form
int (*p)[Cols]

Now, I know you can't do this. So how would I dynamically allocate it to do it?
Teaching me how to do so would really be appreciated!
Comment: *"Now, I know you can't do this. "* - How do you know that? Because that's wrong.
Comment: Add extra `typedef`s in your c code to increase readability. See [this C reference](https://en.cppreference.com/w/c) and compile your C code with [GCC](http://gcc.gnu.org/) invoked with all warnings and debug info: `gcc -Wall -Wextra -g` and [this answer](https://stackoverflow.com/a/19526457/841108)
Answer: You can absolutely use int (*p)[Cols], it's a pointer to array of size Cols (Cols times size of int, in bytes), you just have to allocate memory for it, until you do, it doesn't point to a valid memory location. The constraint is that the allocated memory needs to be in blocks of multiples of Cols:
int (*p)[Cols] = malloc(sizeof *p); //prefered

Or
int (*p)[Cols] = malloc(sizeof(int) * Cols); //alternative

In both of the above expressions, supposing Cols's value is 10, p will point to a block of memory that can take 10 ints.
Usage:
for (int i = 0; i < Cols; i++)
{
    p[0][i] = i;
}

The above expresssions only allocated space for one line of ints, but since p is a pointer to array, you can allocate space for as many of them as you want (given the memory constraints).
Let's assume you want an array with 5 lines and Cols columns:
int (*p)[Cols] = malloc(sizeof *p * 5);

Usage:
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < Cols; j++)
    {
        p[i][j] = i * j;
    }
}

As you (probably) know this kind of construct is primarily used to emulate a 2D array, one of the advantages is that you can then free all the memory with a single free:
free(p);

Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple frees.
Comment: @V_S Why are you assuming an answer won't work instead of trying it?
Comment: cols times sizeof int...
Comment: Yeah, my question was what would be the syntax to do so? Can somebody tell me that?
Comment: Um, I don't think that works since you are not allowed to have Cols there. Cols is not a constant value.... it's from user input.
Comment: @V_S of course you can, where did you get that idea from?
Answer: int (*p)[Cols] = malloc( sizeof *p * Rows );

allocates enough space for a Rows x Cols array of int and assigns the address of that array to p.  You can then access each element as p[i][j].
To deallocate all you need is
free( p );


Why won't Korir offer me work (retrieving the Helm of Winterhold)?

Question: I am playing Skyrim SE on Windows Steam. I have completed the Companions questline but have not started the civil war.
In order to become Thane of Winterhold I need to ask Korir for work and then complete the quest he gives me (to retrieve the Helm of Winterhold from a random location). But when I talk to him, he never offers me the job.

I am level 47
Disposition: (pending)
getStage Favor158: 200 (empty)
getStage Favor257: 200 (empty)

How can I fix this? (Console commands welcome)
Things I've tried (without success):

Setting the stage of Favor158 to 0

Similar questions (with no answers):

https://forums.nexusmods.com/index.php?/topic/2896604-trying-to-become-thane-of-winterhold/
https://gamefaqs.gamespot.com/boards/615805-the-elder-scrolls-v-skyrim/65440015
Other questions relate to getting the "Thane" quest after completing the "Helm" quest, but I can't even get the "Helm" quest
Comment: if someone can confirm the name of the quest as it appears in the game I can check that I don't already have it, thanks
Comment: It's a Miscellaneous (i.e, unnamed) quest.
Answer: The discussion page for this quest on UESP discusses this issue. It seems to be related to the Hearthfire addon.

If you have Hearthfire installed and have any one of the of "Build your own Home quests" started but not completed, you will not be allowed to accept any Thane quests from any other Thanes in any other holds. Even though I had already become a Thane in Hjaalmarch, I had not yet visited the homestead property, nor began construction on the house. Upon visiting the property and building the foundation, the quest completed. I immediately returned to Winterhold and was able to begin and instantly finish this quest.

So if you have Hearthfire installed, try to visit your property and build the foundation. The quest should complete and you'll be able to take "Become Thane of X" quests.
Answer: Becoming Thane of Winterhold is not exclusive to Korir.  Additionally, the Helm quest is a technically radiant quest and doesn't have easily accessible quest triggers.
To ensure all conditions are met to get Korir to talk business, ensure the following are all true:

It is during Korir's normal court hours.  Target 10AM-1PM and you're probably good.
Korir is not under attack
You did not tell Korir "no" if he offered you the task previously.

If you shut Korir down on his request the first time, or broke dialog before he could offer it, it's possible his dialog bugged and he considers it a rejection of the task.   If so, you can either reload a previous save before you met him, or win the war for the Empire.
If the Empire wins Winterhold, via war or just trade in Season Unending, they seat Kraldar as Jarl.  Kraldar will give you the Thane quest of just helping people in the hold, instead of sending you to get the Helm first.
Answer: Finish the Bounty quest first that you can get from the Inn owner.. Interestingly enough, upon getting the Thane quest, I thought I'd be sent off to Yngol Burrow but to Pride of Tel Vos instead


Explain how basic code is working - Eloquent JavaScript book

Question: Here is the code - https://github.com/novaugust/code-wyoming-wiki/blob/master/Day-21.md
here is the info if you want a bigger picture (Eloquent JavaScript by Marijn Haverbeke) - http://eloquentjavascript.net/00_intro.html
I'm new in computer world of programming and I don't understand how simple digits (00110001 etc.) mean 1 + 2 + ... + 10 = 55
I understand
<code>var total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total)
</code>
and

console.log(sum(range(1, 10)));

but 00110001 00000000 00000000 is not 'magic' for me. Can somebody explain it in a 'simple mode'? BTW is is really embarrassing to stop on page 4...
Comment: https://en.wikipedia.org/wiki/Binary_number
Comment: Your binary number actually represents **49**, not 55. From right to left (hey, the same as decimals!): 1 + 16 + 32 = 49.
Comment: Marijn writes "Programs looked something like this" above the binary digits. He did not write that this is the same program. It is just an example.
Comment: Please show the exact code that you are asking about and the results that you are unsure of.
Comment: @Jens Wirth that will explain it. Thanks for all contributors!
Answer: From what I understand you're struggling with the concept of binary. This is very common for a lot of people, even life long coders (you don't really need to know it except for hardware stuff).
Essentially binary works identical to the base-10 number system you already know where:
123 = 1 x 100 + 2 x 10 + 3 x 1
OR
123 = 1 x 10^2 + 2 x 10^1 + 3 x 1^0 (^ means exponent)
In binary there are only 2 digits, 0 and 1. However the place-value idea above is the same:
1001:[1 X 2^3] + [0 x 2^2] + [0 x 2^1] + [1 x 2^0]
To determine the value of 1001 you simply perform the calculation above. As a number grows you just increase the number of place values by increasing the exponent power of 2.
Note: 2^n 2^n-1...2^n-n -> formula for a binary number with n+1 digits
      64 + 32 + 16 + 8 + 4 + 2 + 1 = 1111111 -> first 7 binary place values
Binary is typically not human-readable, however it posses some cool features that make it easier for us to use. Notably converting binary to hexadecimal(base 16 number system) is a cinch.
It may also help to start small, I found once I was comfortable with what 1111, 1010, 0001 etc. I was more confident with binary as a whole.


choosing n-1 out of n sigma notation

Question: I have a conceptual (or notational?) question but I will give an example to make myself clear. Say there are $n$ machines, and the probability of machine $1\leq i\leq n$ to not work in a certain day is $p_i$, how can I write the probability of $n-1$ machines not working in a certain day?
If it was the case that $p_i=p_j=p$ for every $1\leq i,j\leq n$ I think it would have been $(\Pi_{i=1}^{n-1}p)\cdot(1-p)\cdot{n \choose n-1}$, but I fail to see how to write it for the case in which the probabilities aren't the same, since the sigma should somehow run on all choices of $n-1$ out of $n$. Am I making things more complicated than they really are?
Answer: This is the same as a single machine working (let the machine $i$ with probability $1-p_i$), so
$$\sum_{i=1}^n\left((1-p_i)\prod_{k=1,\\k\ne i}^n p_k\right)$$ or
$$\prod_{k=1}^np_k\sum_{i=1}^n \frac{1-p_i}{p_i}.$$

choosing n-1 out of n sigma notation


On the existence of a partition (or being well defined)

Question: Consider an uncountable set, e.g. the interval $A = [0,1]$. If I associate each $x \in A$ with a partition $P_x$ over an interval $B = [1,2]$, is the common refinement of all these partitions $P = \cup_{x\in A} P_x$ necessarily well defined/exists?
Comment: It may be defined however if we take e.g. $P_x = \{1,1+x,2\}$ then $$\bigcup_{x\in[0,1]} P_x = \bigcup_{x\in[0,1]} \{1,1+x,2\} = [1,2], $$
in which case the "partition" is the whole interval, and is no longer a partition in the classic sense.
Answer: Yes, uncountable union is well-defined. It is simply:
$x\in P \leftrightarrow \exists y\in A$ where $x \in P_y $
However, it may not be have certain properties that you wanted to preserve about the original set (for example, whether it is measurable).


HVAC Duct options in floor joists

Question: I will explain what I would "Ideally" want. I would like the HVAC in the basement ceiling to Not require a soffit. Plumbing seems possible because the holes for the most part will be small enough to not affect the structural integrity. So the question is what is possible?
There is also a similar post here. They talk about the limits on what can be done to floor joists. From my understanding, it would not be possible to install any ducts through the floor joists. If I am wrong, please let me know.
Last would be what is the alternative? Is it possible to run the ducts through the roof attic? (I assume that opens a whole different set of issues) Plus that doesn't fix the cold air return which should be on the bottom if I am not mistaken. I would really like to avoid soffits if possible but everything I am researching is pointing that direction.
EDIT: The house is an existing home. The basement floor to ceiling is already at the 8' mark. The joists are typical dimensional lumber (not engineered)
Radiant/Hydronic Heating - The idea is awesome. If I was doing a new construction, this would probably be one of the best options.
"low-volume, high-velocity" ducted system - First time I have seen something like this. Its very interesting. I did read there are some disadvantages like noise and it can be costly to add.
To Clarify a bit more, I would like to keep the costs low so redoing the entire heating/cooling system is probably not going to be an option. (of course it depends on what costs would be). I intended to keep with the conventional heating/cooling and was more or less looking for a way to still it but avoid soffits. The image below is an example of what I had original wanted but it doesn't seem like that is up to standard?
EDIT-Image below is a not my current hvac. Its also a BAD way to do it. Was using it as a reference.
Comment: That is WAY too much hole in the TJIs. IIRC, my 20" tall units allowed me to put a 5" hole in the middle of them. Hope the HVAC contractor has insurance to cover the collapse of the house...
Comment: @KalelWade That looks good - the image helped me a lot, actually, to understand the whole issue; And the warning now seems just right!
Comment: Is this an existing home or new construction? You would like to avoid soffits, but is there room for a dropped ceiling?
Comment: I updated my question.
Comment: @Ecnerwal Ya, figured as much. You get images like these when searching - gets my hopes up.
Comment: When not fully reading the question, it  looks like the image is showing your own current state - could you point out it's not (if that is true)?
Comment: So you have an existing HVAC system. Where are the ducts currently? Are you looking to reroute existing ducts serving the main floor, or are you adding on new ductwork for the basement only?
Comment: @littleturtle Yes I have an existing HVAC. It goes down the center of the house for the most part. Air and Cold Air return. I will be modifying parts of it soon but for the most part, not adding any new extensions to it. When I go to finish the basement, I just had wanted the duct work to be more hidden than a soffit that sticks out.
Comment: @VolkerSiegel Add some extra text to the post. I was thinking of removing the image all together since its a bad example but left it there so the comments made sense.
Answer: One option would be "low-volume, high-velocity" ducted system (manufacturers include SpacePak and Unico) that uses a series of small 2" diameter ducts to distribute air. Depending on the size of your joists, 2" holes may be acceptable. As @Ecnerwal mentioned, mini-splits can be a good option too.
Comment: @KalelWade I'd try to find someone you know who has a high-velocity system and listen to it in operation before getting one installed. That high velocity comes with higher noise levels. I put an HV system in my small house a few years ago and if I had to do it again I'd go with mini-splits, they're much quieter.
Comment: I like the idea around the low volume high velocity systems. It seems like the closest thing without reworking the heating and cooling system all together.
Answer: You could put in a non-forced air heating system - ie, hydronic or radiant, using water in pipes to deliver heat. You could use mini-splits for A/C only or for heat and A/C. You only need space for ducts if you need ducts, and there are plenty of houses without ducts...
Edit: you may be able to work with a wide, shallow duct so you can have a broad, not too deep soffit for the cross-joist duct run. Just be sure to get the sizing sorted out correctly (ie, a 12x12 duct cannot be replaced by a 3x48 duct (same area), as there's a lot more friction in the 3x48, but the correction factors for duct shape are surely available so you could pick a size that will work. It will cost more, but it may resolve your issues with soffits if you don't have to duck under them.
Comment: Since its an existing home, this may not work the greatest. If I was doing a new home, the idea of radiant/hydronic would probably work very well.
Comment: OK. Existing houses normally have existing ductwork, so that was not particularly obvious until your revision.
Comment: Ya, sorry about that - added the clarification. Your information was still helpful though because it does bring up different options.

HVAC Duct options in floor joists


Getting this error message before am able to install ubuntu desktop 16.04.1

Question: Been trying to install Ubuntu desktop on our forensics computer so that it could run alongside Windows 10, but keep on getting stuck on this error message.
<code>[    2.074246] xhci_hcd 0000:04:00.0: ERROR Transfer event for disabled endpoint
 or incorrect stream ring
[    2.074303] xhci_hcd 0000:04:00.0: @00000008694f7580 00000000 00000000 1b0000
00 01038001
[    2.079871] xhcd_hcd 0000:04:00.0: ERROR Transfer event for disabled endpoint
 or incorrect stream ring
[    2.079924] xhci_hcd 0000:04:00.0: @00000008694f7a40 00000000 00000000 1b0000
00 02038001
[    3.080201] sd 12:0:0:0: [sde] Asking for cache data failed
[    3.080244] sd 12:0:0:0: [sde] Assuming drive cache: write through
[    8.734985] usb 3-5: device descriptor read/64, error -110
[   13.951227] usb 3-5: device descriptor read/64, error -71
[   19.279631] usb 3-5: device descriptor read/64, error -110
[   24.495884] usb 3-5: device descriptor read/64, error -71
</code>
Any ideas?
Comment: I should mention that I am trying to install from USB
Answer: Looks like a possible kernel bug related to external USB 3.0 hard disks.  If you do have a USB-connected hard disk, you might try removing it while you install Ubuntu.
If that lets you install Ubuntu, but you get the same problem when you plug the USB hard disk back in, then you might try the workaround in this forum thread (see #12).  Good luck.
Comment: Any idea on how to go about solving the problem? Not really finding anything on the linked source
Comment: Hi @GeorgeApodaca, I edited my answer to give more information.  Good luck!
Comment: thank you @rclocher3. One more clarification, if I may. I've downloaded the ISO image onto a USB stick and am trying to install it to a second hard drive on our forensics computer. The first drive currently has Windows 10 and Win98 DOS. It's this second drive I'm trying to install ubuntu/bitcurator onto.
Comment: Do you have a USB-connected external hard disk, and if so, is that where you're trying to install Ubuntu?
Comment: It's a digital forensics computer (FRED) so it has two HD slots embedded into the tower that connect directly to the computer. So it is not a USB-connected external hard disk (tho perhaps that may be an easier option to consider). The actual Ubuntu/BitCurator ISO image has been loaded onto the USB and connected to the computer so that it will hopefully boot and install onto the second HD that is connected to the tower. Does that make sense?
Comment: I see that you said you're using a USB stick.  Were you able to "Try Ubuntu" when booting from the USB stick, or do you get that error right away when you try to boot, or is it just when you try to install Ubuntu?
Comment: Once the computer turns on, I press F8 which allows me to choose the USB stick as a boot option. When I select Ubuntu from the boot menu, it gives me an Ubuntu load screen but then shortly thereafter gives me the error message I included in the pic. It then continues on to a different Ubuntu loading page, seemingly trying to load the image, but fails and restarts after 5-8 minutes. (Sorry for the late reply!)


How do I easily find primitive species planets in my territory?

Question: I'm playing in a galaxy with many primitive species. I would like to build observations posts over those planets that are within my territory. How do I easily find the locations of these planets?
Answer: Update:
The below still applies, but is all now unnecessary.
As of the 1.5 "Banks" patch, the system has an icon to the right of the system name indicating that there's a primitive civilization with no observation post.

Survey ships will detect primitive civilizations as you survey. As they do, either make a mental note, write it down, or send one of your construction ships there immediately. You could even rename the system in such a way that it reminds you.
Let's say you don't do that. Then, if there are any resources in the system, you will eventually send a construction ship there to build mining or research stations. If you do this by right-clicking on the system from the galaxy view, then "Build Observation Post" will be one of your options. Make sure you include that in the ship's order queue. I usually do it before building the other stations, just to make sure I don't forget.
Let's say that the pre-FTL civilization is the only thing of interest in the system. In this case, you won't ever bother clicking on it to send the construction ship. This is the main scenario where I forget about one of these systems for a while. Because of this, I occasionally right-click on systems with no apparent resources just inside the edge of my borders, just to check.
Let's say you don't do any of that. Then, you can find pre-FTL civilizations in the Contacts menu. There's a checkbox at the top that limits the results to these types of civilizations, but it's not obvious from that view which ones already have an observation post, or are even within your territory. You can figure it out by comparing this list to your list of observation posts, but it's a little tedious.
Comment: With 2.2.3 you can all existing Observation Posts in the Outliner.
Answer: Plan A:  As they come within your borders.
Give your construction ships orders from the Galaxy View Instead of the System View unless you are:

Ordering up a military station.
You are mineral poor.

When a new system enters my borders and I've got a free construction ship, I'll select the ship, and right click on the new system to build any applicable stations.  For those few times a primitive species is in the system, you'll see "build observation post" in the menu between "build research stations" and "build frontier station".  This is the easiest time to build observation posts.
If you do use System view to build your utility stations one at a time, the civilization's icon to the left of their world name should also be a pretty big flag that it is a site for an "alternative research station"
Plan B: Go back after you've already built up the system.
This one is a little more fiddly.  Open up the "Contacts" report and uncheck the 3 boxes at the top which don't represent the (grey) primitive species.  At this stage, you can iterate through the list and click on the camera-like icon to focus your view on their home system.  If they are within your borders, send a construction ship.  Do this a couple times and you'll start to see the virtue of Plan A.
Comment: We'll get icons in Banks so that should make our life easier.


Downclock CPU reaching critical temperature

Question: I have an HP tx1250 laptop. It always had serious overheating problems and although usually it runs fine I'm now running a continuous test for my dissertation, this brings the CPU temp close to the critical and from time to time the computer shutdown for reaching it (checked the log).
I use to have the same problem on Win XP but I noticed Win Vista and 7 downclock the CPU when is necessary to cool it down so I was thinking if the same is possible on Ubuntu 12.
The only program I've found that may do the job is computer temp ( http://computertemp.berlios.de/ ) but it doesn't seems to work under Ubuntu 12.
The inside of the laptop is fairly clean, the thermal paste is quite recent, I'm keeping it lifted from the desk and judjung by the sound of the fan that's running fine as well. The pc in now running between 78 and 91 degrees C  but about once a day it shut down for reaching 95. I need the results of the test it's running pretty soon so it's important that it runs non-stop.
I've though to set the maximum clock of the CPU to slightly less the maximum but then these tests I'm running would take much more time.

Thanks for your answers but I was thinking about something much easier.
Actually I was about to do a bash script reading the temp on lm-sensor and adjusting the frequency but I though there was already some software doing this or Linux itself should.
Answer: On this webpage there is a bash script that will attempt to keep your CPU below a specified temperature. http://seperohacker.blogspot.com/2012/10/linux-keep-your-cpu-cool-with-frequency.html
This script does this by reducing CPU frequency, and it works for my Intel i7 processor.
Shameless plug- I wrote and maintain the above script.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: How important is this test? It seems it isn't important enough to find a different computer to run it on.
Is it important enough to buy some liquid Nitrogen? Liquid Nitrogen is fairly easy to get and not really expensive. If you set a tub of that below your laptop I imagine the cool vapors would be enough to keep your laptop on until the end of your test.
Comment: Using liquid nitrogen, without specialized apparatus, to cool a computer seems like a very bad idea. Liquid nitrogen causes much of the water vapor in the air near it to condense, so you'd likely be bathing your computer in water. Furthermore, it's likely you'd cool at least some parts of the computer's electronics enough that they would stop operating correctly, crack mechanically, or both. Either way, you'd probably run a very high risk of destroying your computer, plus a small but uncomfortable risk of harming yourself from your wet-with-water computer.
Comment: I've been known to ghetto rig a few cooling setups in my day. Electronics will deal with a a fair amount of condensation. Case in point, I put my girlfriend's hard drive in my freezer for three days while I `ddrescued`'d the contents. My first suggestion is to *not* run it on the laptop, but if the laptop will have to do, then it would be trivial to make a liquid nitrogen cooler. You can hold your hand directly above liquid nitrogen so there's no chance of the laptop shattering. The laptop certainly wont get doused with condensate.
Answer: In addition to what Huckle suggested, you could disassemble the laptop and immerse it in oil.
What you would need to do, is to plunge your laptop's innards in a specialized coolant oil that would absorb the heat it would give off, and then using a motor of some sort, send the oil to a radiator where it could be cooled down before being recycled back into the oil tank.
This method would be a cost-effective solution to keeping your laptop cool (as opposed to air cooling alone), and has been proven to increase power usage effectiveness (or PUE) by as much as 35% in some systems.
Here's another possibility: you could use the HP Cloud to run your test; it moves very fast, and it has app. As an HP cloud user, you already have access to a capacity of 1000.
References: oil, cloud.
Comment: Now that SirChairo mentions it, Amazon has the ECC (or EC2 if you prefer) that is very cheap and will likely run your test in a fraction of the time since it will undoubtedly be many times faster than your laptop.


Out of memory loading imageViews

Question: I have a scrollview which has small thumbnails of images loaded via AsyncTask and throws the image URL unto a imageView.
They are added dynamically and then on top, is a main imageView which holds the image of the thumbnail you clicked.
Everything runs great until you have about 10+ images in the thumbnails...
I am loading the mainImage url via the same way as the thumbnails, so when they click an image in the thumb, it loads it up top.
I am recycling the bitmap in the method itself, but it seems to be running out of memory and crashing when loading more than 10 images (thumbnails load ok, but crashes when i click to load the main image)
any help appreciated
this is the code i am using the load the images (thumbnails + main):
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

  protected Bitmap doInBackground(String... urls) {
      String urldisplay = urls[0];
      Bitmap mIcon11 = null;
      try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
      } catch (Exception e) {
          Log.e("Error", e.getMessage());
          e.printStackTrace();
      }
      return mIcon11;
  }

  protected void onPostExecute(Bitmap result) {
      bmImage.setImageBitmap(result);
  }
    }

Answer: just implement this on ur image ... it will reduce ur image by 4 times
public static Bitmap getImage(byte[] image) {
        BitmapFactory.Options config = new BitmapFactory.Options();
        config.inPreferredConfig = Bitmap.Config.RGB_565;
        config.inSampleSize = 4;
        return BitmapFactory.decodeByteArray(image, 0, image.length,config);

    }

Answer: You should read the two following Android official tutorials. They will teach you how to load large bitmap efficiently, and they provide working code samples that we use in our production apps
Displaying Bitmaps Efficiently
Loading Large Bitmaps Efficiently
Comment: I should note, the images are very small (all within 50-60kb in size) i think i am going to check to make sure it's seeing the same size, and not using an absurd amount of memory instead-
Answer: you are not closing the input stream. So all the time when images urls executed input stream objects created which are expensive and causing you OutofMemoryError. add below code after catch block.
in.close();
in = null;

Comment: It's a good idea to close all the open things, but streams don't keep the data in memory. They pass data from input to output. They will also be garbage collected here since `in` goes out of scope after the `try`
Answer: You probably have to work with some sort of cache strategy for the bitmaps, try having a look on the library Universal Image Loader, it works very well for what you need
Recycling bitmaps by yourself should only be done when you know for sure that it won't be used anymore.
Answer: Try to  resize the bitmap to a smaller size (with a factor like 1.5 example: width=widt*1.5)
then strech(fit xy or whatever) in your view.it will lower the quality of the image due to the factor you decide. it is a quick dirty way. also making bit map rgb like Niun Goia mentions works well.
Answer: You shouldn't be using a ScrollView for this. You should be using a ListView. When you use a ScrollView (with a LinearLayout or something like that inside it), all the elements in the list (no matter how big it is) will try to be loaded immediately. Try a ListView instead (which is made for that exact reason, it only loads in memory the ui elements of the rows that are visible).
Comment: I really wanted to keep the images in a scrollview though because it would be nice to let the user scroll sideways through the thumbnails-
Comment: If you are set on doing this with a scrollview, you need to somehow implement yourself the caching of rows. For a good explanation of what I mean, have a look [here](http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/). A very good guide on building your own listview can be found [here](http://developer.sonymobile.com/2010/05/20/android-tutorial-making-your-own-3d-list-part-1/) and [here](http://developer.sonymobile.com/2010/05/31/android-tutorial-making-your-own-3d-list-part-2/).
Answer: You can use android:largeHeap="true" to request a larger heap size
answer
Answer: I use this..
Options opt = new Options();
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inPreferredConfig = Bitmap.Config.RGB_565;

Out of memory loading imageViews


Faster/smarter loops [Python]

Question: Data file is an Excel list with 4 columns: name, position, value and price. File imported with pandas.
There are 5 different positions.
I'm trying to match all different possibilites where it can only be one from each position + one random player that has not yet been chosen.
def teams(x):
    positions = list(data.Position.unique())
    indices = []
    for position in positions:
        indices.append((data.Position == position).nonzero()[0])

    positions.append('Random')
    indices.append(data.index)

    for i in indices[0]:
        for i2 in indices[1]:
            for i3 in indices[2]:
                for i4 in indices[3]:
                    for i5 in indices[4]:
                        for i6 in indices[5]:
                            if i6 != i:
                                if i6 != i2:
                                    if i6 != i3:
                                        if i6 != i4:
                                            if i6 != i5:
                                                print i, i2, i3, i4, i5, i6

teams(data)

My problem is that my loops are too slow and I can't get the if statement to work so I have to make 5 different ifs, which I assume is a pretty stupid solution.
My question is: how can I make my loops faster/smarter and how do I fix my if statement
Comment: you could do `if i6 not in [i,i2,i3,i4,i5]` for your if statements
Comment: How many elements are in each indices?
Comment: atm its about 10 in all expect the last one which have about 50
Answer: You can shorten your code to three lines if you use itertools.product() like so
from itertools import product

for i in list(product(*indices)):
    if i[5] not in i[:5]:
        print i[0], i[1], i[2], i[3], i[4], i[5]

product() is equivalent to nested for loops
Comment: @Svelic I can't think of any other way to do it. If each indices has 10 elements and the last one has 50 then you are looking at 5 million possibilities. Caching might be an option but I don't see how to apply it to this problem. Sorry
Comment: this code is indeed shorter but its still really slow. Is there anyway to make it faster?

Faster/smarter loops [Python]


Condition number example

Question: I have been learning about the condition number, i.e $$cond_p(A) = ||A||_p||A^{-1}||_p.$$
I've been considering the $2$ norm, and have been thinking about when the condition number is equal to $1$. Of course, when $A = I$ this holds, but I can't think of any other examples?
Thank you.
Comment: Orthogonal matrices are an example.
Comment: The condition number of a matrix can only equal to one if the mapping defined by the matrix is a (scalar multiple of) a linear isometry. That such a matrix is necessarily orthogonal (or unitary in the complex case) in the 2-norm was shown here:
https://math.stackexchange.com/questions/169923/proving-that-a-linear-isometry-on-mathbbrn-is-an-orthogonal-matrix
Thus, @NigelOvermars example pretty much covers it, up to multiplication by a scalar.
Answer: When $A$ is an orthogonal matrix, then $A^T = A^{-1}$.
Hence, for an orthogonal matrix $A$, we have $A^T A = I$.
It follows that $\lambda_{\max}(A^T A) = 1$.
Hence, for an orthogonal matrix $A$, $\Vert A \Vert_2 = 1$.
(Every orthogonal matrix is well-conditioned).
In a similar way, we can show that $\Vert A^T \Vert_2 = 1$.
(If $A$ is orthogonal, then $A^T$ is also orthogonal.)
Thus, $\Vert A^{-1} \Vert_2 = 1.$
Hence, for any orthogonal matrix $A$,
$\kappa(A) = \Vert A \Vert_2 \, \Vert A^{-1} \Vert_2 = 1$.
(Orthogonal matrices are well-conditioned matrices.)

Condition number example


Behaviour of preincrement operator

Question: Consider the following code:
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char **argv) {
  vector<int> v = { 1 };
  auto it = v.begin();
  cout << ++(*it) << " " << v[0] << " " << endl;
  cout << v[0] << endl;
  return EXIT_SUCCESS;
}

When compiled and run, this code yields the following console output:
2 1
2

Given that ++(*it) increments the first vector value, I would instead expect the following output:
2 2
2

Why isn't the increment reflected in the first cout statement for v[0]?
Comment: There isn't a defined sequence point within the expression at which the ++ operator should be applied.
Comment: I cant figure out why someone has downvoted my question?
Answer: The reason being,:
cout<<++(*it);

is printing the next value 2 but the original value of v increases only after the the line:
cout<<++(*it)<<" "<<v[0]<<" "; // v[0] is still `1`

Now the value v[0] is incremented and result is 2
cout<< v[0]<<" ";

You can increment before the cout
++(*it);
cout<<*it<<" "<<v[0]<<" ";

Now the output will be the same.
Answer: ++(*it) will increment and return the element it refers to, not the iterator itself, so v[0] is 2 after evaluating that expression.
So why doesn't it print 222?
Because the chain of operator<<s is actually nested function call, somewhat like this:
operator<<(operator<<(operator<<(operator<<(std::cout, ++(*it)), " "), v[0]), " ");
and the bit of interest:
operator<<(operator<<(std::cout, ++(*it)), " "), v[0])
This is a function call with two arguments, operator<<(std::cout, ++(*it)) and v[0].
The order in which function arguments are evaluated is unspecified, one platform or compiler may do it differently than another (left to right and right to left are common, as far as I know).
If the second argument is evaluated first, v[0] is retrieved while still holding 1, and we print 212.
If the first argument is evaluated first, ++(*it) happens first, and v[0] is retrieved after, so we print 222.
Unfortunately, the C++ standard only guarantees that the evaluation of all arguments is sequenced before the  function body, but not with respect to each other.
Using both v[0] and ++v[0] in unsequenced expressions may invoke undefined behavior - which could do exactly what you want, or launch the missiles.
Comment: You are right about the fact that its actually an overloaded function call and there are no guarantees about the evaluation of arguments.But this gives me another doubt-What does the concept of left associativity of << operator mean then?(overloaded<< is also left associative).Shouldnt left associativity ensure that first arguement is  always evaluated first?
Comment: @TarunBhargava left-associative only means `a << b << c` groups like `((a << b) << c)`, and a right-associative operator like `=` groups like `(a = (b = (c = 4)))`

Behaviour of preincrement operator


What should I do about soaked particle board under my kitchen sink?

Question: I recently discovered I have a leaky garbage disposal (that i have yet to fix). I think it had been leaking for a while, and it has caused the particle board beneath the kitchen sink to sag. I have been catching the drip for a few days now, but it doesn't seem to be drying, and it still feels damp. It's starting to smell a bit like mildew too.
The question is two fold:

Do I need to replace the particle board? It's a corner sink, and I don't think I could replace it without taking the cabinet face off.
If I don't replace the particle board, what's the best way to dry that space and remove the smell.
Answer:
Remove cabinet door.
Fix leak.
Remove particle board and put a box fan blowing into the cabinet for at least 24 hours. Treat the floor under there with a mold killing cleaning spray. Put the fan back while you cut the new bottom. I would do it piecemeal before removing the face of the cabinet. Which you may have to because removing the face of a corner cabinet will only give you another 2 inches or so. You would have to pull the counter top and remove the top of the cab to get a full piece in there. You may need a support under the planks in the middle somewhere but it beats destroying your kitchen.
Comment: +1 Any attempt to just dry the old particle board creates a substantial risk of a mold problem.
Comment: Well that stinks, but I guess I gotta do what I gotta do. Thanks.
Comment: I did the same thing when I moved into this house ten years ago.  You can do it, and you are allowed to curse as you do.
Answer: Fix the leak.Dont bother drying anything.Remove all traces of particle board and any other damaged wood. Check cabinet sides for structural integrity as well as exposed toe kick panel in front. check the floor under the compromised particle board. If all is well then obtain 2 60lb.or 80lb. bags of ready mix concrete. Mix and pour new floor in place. Smooth.
After it has cured it may be painted to suit. This will also take care of any mildew smell.
Comment: Hello, and welcome to Stack Exchange. Why are you recommending concrete?


Hide web page source code

Question: I wonder how to hide the source code of a web page. This is an example of webpage with hidden source (right click -> view page source). Any ideas or suggestions?
UPDATE I fully agree, that fully hiding HTML source is impossible, otherwise the browser could't parse it. Using tools like FireBub etc. will show you the source. The interesting in the example above in that on "show source code" the displayed page does not match the output.
Now I understand it is just another kind of technology used here - XSLT.
Thanks for your replies!
Comment: That technique prevents only the most novice users from looking at the source code...in other words, it does absolutely nothing.
Comment: It isn't hidden, it's just using XML and [XSLT][1]. All the page's code is at https://e-fibank.bg/EBank/xslt/login.xslt.

  [1]: http://en.wikipedia.org/wiki/XSLT
Comment: The source of your link is this: `

BG

Login
При проблем със зареждане на сайта, моля опитайте  /
 If you can't access the site, please try: https://e-fibank.bg/EBank/Mobile
`
Comment: You can disable right click through javascript, but there will always be some way to see the output code
Answer: If your page is generated dynamically (by Javascript), then it using View Source will not show anything (or very little, anyway). I suspect that's how your example is doing it.
Bear in mind that any page generated this way will still be visible by using a code inspector such as Firebug. So as @Brad M says, this will only stop people who don't really know what they're doing.
If you build the entire page in Java or Flash (or something similar like Silverlight I guess) then it's a lot harder for someone to find out what the source code is (though Java is pretty easy to decompile)
Comment: so if they run a transform on the client side, and inject the result into the dom, that's not rendering client side?
Comment: agreed, took a look at the page, they are rendering client side
Comment: @TimMac No they aren't. They're loading static content with XSLT.
Answer: There is no way to hide your code from a client that must execute the code.
Your example just did some trick to prevent right-clicking and stuff. But eventually you can get your way around.
Answer: For interpreted language such as javascript, the following adage is true.
" Lock on the door is only for the one who don't care. If there comes thief, most of the time he is already prepared."
All you can do to prevent is obfuscating your code. That will prevent it for some time. But remember, if they are going to crack it, it is not unstoppable. The basic thing to remember is: your script is going to run on the client side and is "INTERPRETED" by browser. In these days, when there are few tools that can create source code from compiled file, the thought of hiding javascript code is even not thinkable. This How can I obfuscate (protect) JavaScript? can help you on how to do it.

Hide web page source code


Is it possible to add description to an array type in Typescript?

Question: I have the following type(s):
const type Person = [string, number, number]

const type Person = [
  string, // name
  number, // age
  number // height
]

Is it possible to add comments to what the elements are? Or any conventions? Like with function: Where is the syntax for TypeScript comments documented?
Comment: Why aren't you using typed objects (with properties)? Or classes? https://www.typescriptlang.org/docs/handbook/2/classes.html
Comment: @birgersp Because sometimes an array is the correct tool, the specific type description given as an example isn't all that important for the question imo. A good example would be coordinate systems where you often work with tuples of different kinds and it would be very handy to know which one is longitude and which is latitude etc, since they differ between different systems.
Comment: @birgersp Thanks for the idea. I have to migrate data to a new schema and the new type is an object. But the old data is not changeable. :/
Answer: I think the closest solution is Labeled tuple elements
const type Person = [name: string, age: number, height: number]

Comment: That's perfect! Exactly I was looking for! Great IntelliSense in VSCode now.
Comment: @LarsFlieger please keep in mind, labels are acting almost like comments, they don't affect your types or runtime code in any way


Arrows for Navigation/Menu/Expandables Misleading?

Question: When a user visits a site they are presented with some sort of Navigation Structure. Typically the arrow is a standard convention that alerts a user that when this item is clicked an action will occur. It can be presented from expandable side navigation, returning to a previous page to other multiple actions.
Throughout navigating various websites on personal computers to mobile devices I have noticed that arrows can be a bit misleading. Some sites give the impression their side-navigation expands but once you click the item the user is directed to another page or vice-versa.
Through research I have noticed sites like Think Geek using arrows to direct users to new pages while plus signs are used to display expandable content.

CSS-Tricks uses a longer version of the arrow that directs users to a new page with more information.

You-Tube has used arrows on multiple items that almost seem to be over-abundant, unneeded, and a little confusing.

Can Arrows have multiple uses from expanding content to directing users to a new page? Are there any best practices regarding the usage of arrows on websites?
Answer: Arrows always designate direction and movement and guide the eyes to wherever arrows point.
The one thing to always keep in mind is to keep things consistent - ideally, adhere to general standards of the platform or media you are working in, but if in doubt, at least do keep things consistent in your own domain.
Here is a UX.SE question concerned with expand arrows and here you can find an insteresting article about arrows in general
Answer: Arrows, like any symbol, can take on whatever meaning you desire, but realize you also need to take into account the 'typical uses' that people are already accustomed to.
In your examples, I see fairly common and consistent uses. Arrows pointing to the right indicate 'going to some content'
Arrows (or, more specifically, triangles) pointing down refer to drop-down menus or expandable content.
And there are exceptions, of course. Often expandable content may also be indicated with a right-arrow, but preceeding the text as such:
<code> > expandable content

\/ expanded content
</code>
(I believe this originated from the original Macintosh OS)
And +/- also work as well (made common with early Windows OSes)
Comment: I have an accordion style row element. I do know about the convention if arrows precede the content. Which is arrows pointing right in collapsed state and down in expanded state. In my design I have the arrows to the right of the content since I have checkboxes on the left. Where should my arrows point?
Comment: @imbakaran that's a good question. You should post it as a question rather than a comment/answer. If you can, show a wireframe/visual as well.


System.Data.SqlClient.SqlException: 'invalid object name EmpUpdate'

Question: Service1.cs
<code>namespace WcfServiceLibrary1
{
    public class Service1 : IService1
    {
        public getempupdate[] Update(string EName)
        {
            {
                getempupdate g = new getempupdate();
                SqlConnection con = new SqlConnection("Server=localhost;Database=master;Trusted_Connection=True");
                con.Open();
                SqlCommand cmd = new SqlCommand("select EID, EName, EUpdate from EmpUpdates with (nolock) where EName = @EName", con);
                cmd.Parameters.AddWithValue("@EName", EName);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt); //Getting the error on this line
                con.Close();
                g.EmpUpdates = dt;
                return dt.ToList<getempupdate>().ToArray();
            }
        }
    }
}
</code>
Comment: Master database is a SQL Server reserved database, not intented for user data.
Answer: This would normally indicate that the table does not exist. Check you spelled it correctly.
Also looks like your connection string points to a database called 'master'. That's probably wrong. What is your database name?
Comment: hello Steve, my database name is EmployeeUpdate. Also I checked my table EmpUpdates does exist in database. I'm new to this, what should I do next? Thank you.
Comment: I got the issue i had forgotten to add my db name in the query above. Thanks for your help!


I can't add items to cart in a shopping app by redux in react native

Question: I am trying to create a simple shopping app, I use redux and react-navigation in my project.
There is a Homescreen, Books screen and Cartscreen.
I've imported items via a simple array namedbooks into Books screen
This is the codes into Books screen:

import { useDispatch} from 'react-redux';
import { addSomething} from '../actions';
import { books } from '../data/fakedata';

const Books = (props) => {

  const { navigation } = props;
  const dispatch = useDispatch();

const bookProduct=(books)=>{

return books.map((item, index)=>{

return(
  <TouchableOpacity
  key={index}
  onPress={()=>dispatch(addSomething(books))}
  >
<Text style={{color:'white'}}>{item.name}- {item.price}</Text>
  </TouchableOpacity>

)})}

return (
      <View >
              {bookProduct(books)}
      </View> )}

This the action file:
export const addSomething = (books) => {

    return (dispatch) => {

        dispatch({
            type: 'ADD',
            payload: books
        })

    }

}
export const removeSomething = (books) => {

    return (dispatch) => {

        dispatch({
            type: 'REMOVE',
            payload: books
        })

    }

}

This is the Header component into Books screen which hold an state and would be updated after each click on items:

import {useSelector} from 'react-redux';

const Header =(props)=>{

 const {navigation }=props;
 const counter=useSelector(state=>state.cardR.counter);

return(
<Fragment>

<Icon onPress={()=>navigation.navigate('Cart')}  />

<Text>{counter}</Text>

</Fragment>
)}

This is the reducer file:

const initialState={
counter:0,
item:''

}

export default (state=initialState, action)=>{

switch (action.type) {
    case 'ADD':
        return {counter:state.counter+1,item:action.payload}
        break;
    case 'REMOVE':

         return something else

        break;

    default:
        return state;
}}

This is Combinereducer file::

import {combineReducers} from 'redux';
import cartReducer from './cartReducer';
import visibleReducer from './visibleReducer';

export default combineReducers({

cartR:cartReducer,
visibleR:visibleReducer

})

And this is the store file:

import {createStore, applyMiddleware} from 'redux';
import reducers from './reducers';
import thunk from 'redux-thunk';

const initialState={

    cardR:{counter:0, object:''},
    visibleR:{visible:false}

}

export const store = createStore(reducers, initialState, applyMiddleware(thunk) );

My problem:
I can update state {counter} in header when user click on a item in Books`` screen but i need to add items intocart``` screen at the same time with that click, but it doesn't happen
I would be grateful if you help me to solve it out
Answer: <code>//item, not books
onPress={()=>dispatch(addSomething(item))}
</code>
Also you can remove initialState from
<code>export const store = createStore(reducers, initialState, applyMiddleware(thunk) );
</code>
Cause you are setting up initialState for each reducer directly
Updated code for <code>reducer</code> file
<code>const initialState={
counter:0,
items: [],

}

export default (state=initialState, action)=>{

switch (action.type) {
    case 'ADD':
        return {counter:state.counter+1, items: [...state.items, action.payload.item]}}
        break;
    case 'REMOVE':

         return something else

        break;

    default:
        return state;
}}
</code>
Comment: so in this case try to change this part of the store file
```
const initialState={

    cardR:{counter:0, object:''"},
    visibleR:{visible:false}

}
```
to
```
const initialState={

    cardR:{counter:0, items: []},
    visibleR:{visible:false}

}
```
Comment: Thanks buddy, I changed my code to what you said but it didn't work, I can't remove ```initialState``` from ```const store``` because i am using ```combineReducer``` and i need to import ```initialState```  again in ```store``` I changed reducer to this: ```{counter:state.counter+1, items: [...state.items, action.payload.item]}}``` but i am getting this error when i click on items in ```Books``` screen : Type error: invalid attempt to spread not iterable instance```
Comment: Thanks for your time buddy, but issue is persisting, I don't see any error anymore but
 book items don't add to ```cart``` screen, I should say ```count``` is updating in ```Header```with each click without any problem, Do you have any idea?


Application Lifetime and Add Singleton DI service in ASP.NET Core

Question: I am trying to understand the singleton lifetime in the context of DI in ASP.NET Core.
First, from what I can see a Singleton instance will be available "across application lifetime." But what does "application lifetime" mean? If it's a website and if a user logs in, singleton created first and user logs out and comes back in to the site after a few hours and logs back in will that user gets the same singleton instance? what about multiple users? Can multiple users get the same singleton instance?
Second, When does application lifetime end in .NET Core? Most articles talk about registering for application shutdown events. But what triggers an application shutdown? Is it always external events like IISreset or a system shutdown? Or internal events like memory crash etc? If no resets or memory or any other issues, will it keep going forever?
Comment: Here you have the microsoft docs, essentially a Singleton service is instantiated only once when the app "starts", and that single instance is the one being used everywhere. It has nothing to do with users. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes
Answer: Singleton here (i.e. not the singleton design pattern) means a single instance for the created root IServiceProvider, so effectively a single instance will be used for all requests, until the process exits.
It has nothing to do with per request or session. If you want a new instance per request, but shared, use the scoped lifetime.
Comment: An important distinction between the Singleton Design Pattern and the Singleton Lifestyle is that with the Singleton Design pattern there will be at most 1 instance for the complete app domain. With the Singleton lifestyle, however, if you create multiple DI Container instances (so multiple "root `IServiceProvider" instances, as Daniel notes), there will be at most one instance *per provider*.


How can I summarize a count() of multiple tables and include a 0 instead of null when no rows are returned

Question: I want to count the number of rows that have been generated today across multiple tables, then summarize this information in a table with the source table name and the count. I have been able to do this using union withsource.
However, if no rows are returned from a table then it is missed out of the summary. Instead I want to return a count of 0 if there are no rows and still include the table in the summary. Is this possible?
I think I need make-series but I can't figure out how to format the query.
Example
Today is: 2022-11-21
TableOne

RowId
TimeGenerated

1
2022-11-21

2
2022-11-21

3
2022-11-19

TableTwo

RowId
TimeGenerated

1
2022-11-19

2
2022-11-18

Kusto
union withsource=source TableOne, TableTwo
| where TimeGenerated >= ago(1d)
| summarize dcount(TimeGenerated) by source

Actual Output

source
dcount_TimeGenerated

TableOne
2

Desired Output

source
dcount_TimeGenerated

TableOne
2

TableTwo
0
Comment: The data does not match the results.
Comment: `dcount(TimeGenerated)` does not make any sense when you're filtering on a single day.
Answer: set query_now = datetime(2022-11-22);
let TableOne = view()
{
   datatable(RowId:int, TimeGenerated:datetime)
   [
       1 ,datetime(2022-11-21)
      ,2 ,datetime(2022-11-21)
      ,3 ,datetime(2022-11-19)
   ]
};
let TableTwo = view()
{
   datatable(RowId:int, TimeGenerated:datetime)
   [
       1 ,datetime(2022-11-18)
      ,2 ,datetime(2022-11-17)
   ]
};
union withsource=source TableOne, TableTwo
| where TimeGenerated >= ago(3d)
| summarize dcount(TimeGenerated) by source
| join kind=rightouter datatable(source:string)["TableOne", "TableTwo"] on source
| project source = source1, dcount_TimeGenerated = coalesce(dcount_TimeGenerated, 0)

source
dcount_TimeGenerated

TableOne
2

TableTwo
0

Fiddle
Comment: This does seem to do the job. I've actually added more tables and replaced dcount with a regular count based on the feedback. I'll happily accept the answer but it might be useful if you explain a little about why it works in the answer. Thank you!
Comment: If you union 100 tables but only one table has data, you are going to see only one record in the result set. The summarize operator is not aware of your data sources, it generates a result row per aggregation key. If we want to verify that we get a row per data source, we need to create those rows.


Best Approach To Testing App Appearance In Flutter While App Is In Dark/Light Theme (especially for Dark Theme)

Question: After going through the Flutter docs on testing, I have come to a point in my app where I would like to test both light and dark theme appearance on the app. Integration tests could be an option, however they are "expensive" to run and I would like to leave the consideration of integration tests as a last resort on the matter of testing for dark/light theme app appearance.
This is what I tried with (Widget Tests) testWidgets:
void main() {
  testWidgets("Test that the app renders properly in 'Dark Theme'.",
      (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.dark(),
        home: RegistrationHomePage(),
      ),
    );

    expect(
      SchedulerBinding.instance.window.platformBrightness,
      Brightness.dark,
      reason: "The test suite should now be testing with app theme set to dark theme.",
    );
  })
}

However, this test failed. It failed because the Widget Test is still executing this test in light theme instead of dark theme.

What can be done to remedy this situation and how feasible is it to run Widget Tests (focused on app appearance)?
Should the universal default for testing app appearance in flutter be an Integration Test?

Update:
Realistically, I am testing the color that a text widget would be displayed in [both in light theme and dark theme].
main.dart
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.system,
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      home: RegistrationHomePage(),
    );
  }
}

registration_screen.dart
class RegistrationHomePage extends StatefulWidget {
  // Constructor
  RegistrationHomePage({Key key}) : super(key: key);

  @override
  _RegistrationHomePageState createState() => _RegistrationHomePageState();
}

class _RegistrationHomePageState extends State<RegistrationHomePage> {
  void setState(fn) {
    super.setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          "Welcome to the app",
          style: TextStyle(
            color: MediaQuery.of(context).platformBrightness == Brightness.dark
                ? Colors.green.shade900
                : Colors.green,
            fontWeight: FontWeight.w600,
            fontSize: 35.0,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}

test.dart
void main() {
  testWidgets("Test that the app renders properly in 'Dark Theme'.",
      (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.dark(),
        home: RegistrationHomePage(),
      ),
    );

    final Finder loginTextFinder = find.text("Welcome to the app.");
    final Text loginText = tester.firstWidget(loginTextFinder);

    expect(
      WelcomeText.style.color,
      Colors.green.shade900,
      reason:
          'While the system dark is dark theme, the text color should be dark green',
    );
  });
}

The test fails. The test fails because the tests have been carried out with the app set to light theme instead of dark theme. There must be something I'm doing wrong here. For now it seems like I cannot set the test app to dark theme which I have tried to do in test.dart with
void main() {
  testWidgets("Test that the app renders properly in 'Dark Theme'.",
      (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData.dark(),
        home: RegistrationHomePage(),
      ),
    );
  });
}

Comment: I would not test the direct MaterialApp theme implementation, the flutter team has done thast for you :).  I would test the logic that handles theme switching.
Comment: Thank you so much for you comment. It's been very helpful in thinking about the problem form a different direction [I'm still thinking about it though]. Now that I have updated the question, do you think there's anything else I could do?
Answer: This is the route I would take if I am running a widget test for an app in dark theme:
void main() {
  testWidgets("Test that the app renders properly in dark theme",
      (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      theme: ThemeData(brightness: Brightness.dark),
      home: RegistrationHomePage(),
    ));

    // Capture a BuildContext object
    final BuildContext context = tester.element(find.byType(MaterialApp));

    // Get finders and relevant objects that would be available at first load of MaterialApp()
    final Finder welcomeTextFinder = find.text("Welcome to the app");
    final Text welcomeText = tester.firstWidget(welcomeTextFinder);

    // functions
    bool testIsInLightTheme() {
      /// return true if the test is in light theme, else false
      if (Theme.of(context).brightness == Brightness.light) {
        return true;
      }
      return false;
    }

    // Here is just a test to confirm that the MaterialApp is now in dark theme
    expect(
      Theme.of(tester.element(find.byWidget(welcomeText))).brightness,
      equals(Brightness.dark),
      reason:
          "Since MaterialApp() was set to dark theme when it was built at tester.pumpWidget(), the MaterialApp should be in dark theme",
    );

    // Now let's test the color of the text
    expect(
      welcomeText.style.color,
      testIsInLightTheme() ? Colors.green : Colors.green.shade900,
      reason:
          "When MaterialApp is in light theme, text is black. When Material App is in dark theme, text is white",
    );
  });
}

Some notable mentions:
Capturing a BuildContext object in test: https://stackoverflow.com/a/67704136/7181909
Standard instruction (basically some flutter source code that dealt with theme testing) on how theme testing should be approached [By the Flutter team that contributed to theme related testing!]
Answer: In case you need to change the brightness during the test, you can use the platformDispatcher's platformBrightnessTestValue property
inside the test:
widgetTester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
globally:
TestWidgetsFlutterBinding.instance.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
Just remember to pump after you change the value
Answer: HEre is my short solution, based on @Alvindera97 answer:
  Future<void> testDarkMode(
    WidgetTester tester, {
    required keyElementToCheckDarkmodeIn,
    required keyDarkmodeSwitcher,
  }) async {
    expect(
      Theme.of(tester.element(_finder.key(keyElementToCheckDarkmodeIn))).brightness,
      equals(Brightness.light),
    );

    await tester.tap(_finder.key(keyDarkmodeSwitcher));
    await tester.pump();
    await tester.pumpAndSettle(_testUtils.delay(DELAY));

    expect(
      Theme.of(tester.element(_finder.key(keyElementToCheckDarkmodeIn))).brightness,
      equals(Brightness.dark),
    );
  }

  Finder key(String keyText) {
    return find.byKey(Key(keyText));
  }


Responsive React App via CSS

Question: Right now, my app looks almost exactly how I want it too via larger screens. https://imgur.com/a/MCe5D - As you shrink the screen size down, the two columns (trending up and trending down) will get closer and closer until they are just about touching, which is great. But at that instance when they no longer get any closer, I would like to have the Trending Down and it's contents move underneath the Trending Up column, to be more mobile friendly. Here's a pen showing the area that is being affected.
<code>//The whole area surrounding the two columns
.playersColumns {
display: flex;
flex-direction: row;
justify-content: space-evenly;
padding-left: 150px;
padding-right: 150px;
padding-top: 25px;
overflow-y: scroll;
}

//The two columns of player info
.playersBody {
overflow: auto;
flex-direction: column;
justify-content: center;
flex-wrap: wrap;
min-width: 255px;
}
</code>
That pen isn't very useful, but it shows my exact code and which tags are where. I tried putting the 2nd column of player info and trend header inside of the first one, but that just made it one large column (which is what I want, but only when the screen is shrunk)
Any help is appreciated — if there is a better way to display the code or layout, let me know.
Answer: I recommend looking into Media Queries.
Here is a short video to show you the basics.
You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.
<code>@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}
</code>

Responsive React App via CSS


Let $f: N -> N$ be a fucntion satisfying $f(n+m) = f(n) + f(m)$ for all $m$ and $n$. Prove that there exist a constant $c$ so that $f(n) = cn$.

Question: The question is actually Example 2.6 from A walk through combinatorics. The solution given below is exactly as in book.

Let $m = 0$, then $f(n + 0) = f(n) + f(0)$, so $f(0) = 0$, and the base case is
  complete. Now let us assume that we know the statement is true for all natural
  numbers less than or equal to $n$. That is, there exists a constant $c$ so
  that $f(k) = ck$ if $k \leq n$. In particular, that means $f(1) = c$ and
  $f(n) = cn$. This implies that $f(n+1) = f(n) + f(1) = cn + c = c(n+1)$, and
  the statement is proved.

Is the proof correct? I mean in induction it uses the fact that $f(1) = c$ which is not proven in the base step. And even if we try to prove it the similar way as we are doing in induction step for $f(n+1)$, we will get $f(1 + 0) = f(0) + f(1)$, thus $f(1) = f(1)$ not $f(1) = c$ which we want.
Comment: That $f(1)=c$ is automatic, since it is a function and it is well defined, so $1$ is sent to some unique natural number $c$.
Answer: $f(1)$ has to equal something,  Call it $c$.
Answer: If that induction step is difficult to understand, you can do it directly and see why $f(1) = c$ (it's not a given constant, it's what you'll have to show):
$$f(n) = f(n-1 + 1) = f(n-1) + f(1) = f(n-2)+f(1)+f(1) = \cdots = nf(1)$$
so that constant is indeed $f(1)$.


I reset password in the recovery mode, but still unable to login in ubuntu

Question: I booted in recovery mode and then typed:
mount -o rw,remount / passwd username

I got numerous options, none of them worked. Then I type passwd and hit enter. It asked for new password, I reset the password and exited the root system then tried to login, but it said the password is incorrect.
Answer: "passwd" in recovery mode will set the root password, which is a bad idea. You need to use "passwd username" instead, where "username" is your actual username. Assuming your username is "u", the following two commands will do the trick:
mount -o remount,rw /
passwd u

Also, you should reset the root password to fix what you've already done:
passwd -dl root