text:
Q: GDAL - Warp image to inverted y-axis coordinate system (Apple MapKit) gives image upside down I'm having an image of a map that I want to geo reference and overlay on the built-in map on iOS. I'm using GDAL programmatically.
Step 1 (OK) - Geo referencing (works fine)
Currently I'm calculating a GeoTransform (the 6 coefficients) from three ground control points to geo reference the image and it gives me the correct 6 coefficients.
Step 2 (PROBLEM) - Warp image + get GeoTransform for new transformed image
The image becomes upside down! This is because the target coordinate system (Apple's own coordinate system in MapKit) has inverted y-axis which increases as you go south.
Question
How can I get GDAL to warp the image correctly (and at the same time give me a correct GeoTransform to go with it)?
What I've tried
I changed value 5/6 in the original GeoTransform before warping. This gives a correct warp of the image, but the new GeoTransform is wrong.
CURRENT CODE
- (WarpResultC*)warpImageWithGeoTransform:(NSArray<NSNumber*>*)geoTransformArray sourceFile:(NSString*)inFilepath destinationFile:(NSString*)outFilepath
{
    GDALAllRegister();

    GDALDriverH hDriver;
    GDALDataType eDT;
    GDALDatasetH hDstDS;
    GDALDatasetH hSrcDS;

    // Open the source file.
    hSrcDS = GDALOpen( inFilepath.UTF8String, GA_ReadOnly );
    CPLAssert( hSrcDS != NULL );

    // Set the GeoTransform on the source image
    // HERE IS WHERE I NEED NEGATIVE VALUES OF 4 & 5 TO GET A PROPER IMAGE
    double geoTransform[] = { geoTransformArray[0].doubleValue, geoTransformArray[1].doubleValue, geoTransformArray[2].doubleValue, geoTransformArray[3].doubleValue, -geoTransformArray[4].doubleValue, -geoTransformArray[5].doubleValue };
    GDALSetGeoTransform(hSrcDS, geoTransform);

    // Create output with same datatype as first input band.
    eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDS, 1));

    // Get output driver (GeoTIFF format)
    hDriver = GDALGetDriverByName( "GTiff" );
    CPLAssert( hDriver != NULL );

    // Create a transformer that maps from source pixel/line coordinates
    // to destination georeferenced coordinates (not destination
    // pixel line).  We do that by omitting the destination dataset
    // handle (setting it to NULL).
    void *hTransformArg = GDALCreateGenImgProjTransformer( hSrcDS, NULL, NULL, NULL, FALSE, 0, 1 );
    CPLAssert( hTransformArg != NULL );

    // Get approximate output georeferenced bounds and resolution for file.
    double adfDstGeoTransform[6];
    int nPixels=0, nLines=0;
    CPLErr eErr = GDALSuggestedWarpOutput( hSrcDS, GDALGenImgProjTransform, hTransformArg, adfDstGeoTransform, &nPixels, &nLines );
    CPLAssert( eErr == CE_None );
    GDALDestroyGenImgProjTransformer( hTransformArg );

    // Create the output file.
    hDstDS = GDALCreate( hDriver, outFilepath.UTF8String, nPixels, nLines, 4, eDT, NULL );
    CPLAssert( hDstDS != NULL );

    // Write out the projection definition.
    GDALSetGeoTransform( hDstDS, adfDstGeoTransform );

    // Copy the color table, if required.
    GDALColorTableH hCT = GDALGetRasterColorTable( GDALGetRasterBand(hSrcDS, 1) );
    if( hCT != NULL )
        GDALSetRasterColorTable( GDALGetRasterBand(hDstDS, 1), hCT );

    // Setup warp options.
    GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
    psWarpOptions->hSrcDS = hSrcDS;
    psWarpOptions->hDstDS = hDstDS;

    /* -------------------------------------------------------------------- */
    /*      Do we have a source alpha band?                                 */
    /* -------------------------------------------------------------------- */
    bool enableSrcAlpha = GDALGetRasterColorInterpretation( GDALGetRasterBand(hSrcDS, GDALGetRasterCount(hSrcDS) )) == GCI_AlphaBand;
    if(enableSrcAlpha) { printf( "Using band %d of source image as alpha.\n", GDALGetRasterCount(hSrcDS) ); }

    /* -------------------------------------------------------------------- */
    /*      Setup band mapping.                                             */
    /* -------------------------------------------------------------------- */
    if(enableSrcAlpha)
        psWarpOptions->nBandCount = GDALGetRasterCount(hSrcDS) - 1;
    else
        psWarpOptions->nBandCount = GDALGetRasterCount(hSrcDS);

    psWarpOptions->panSrcBands = (int *) CPLMalloc(psWarpOptions->nBandCount*sizeof(int));
    psWarpOptions->panDstBands = (int *) CPLMalloc(psWarpOptions->nBandCount*sizeof(int));

    for( int i = 0; i < psWarpOptions->nBandCount; i++ )
    {
        psWarpOptions->panSrcBands[i] = i+1;
        psWarpOptions->panDstBands[i] = i+1;
    }

    /* -------------------------------------------------------------------- */
    /*      Setup alpha bands used if any.                                  */
    /* -------------------------------------------------------------------- */
    if( enableSrcAlpha )
        psWarpOptions->nSrcAlphaBand = GDALGetRasterCount(hSrcDS);

    psWarpOptions->nDstAlphaBand = GDALGetRasterCount(hDstDS);

    psWarpOptions->pfnProgress = GDALTermProgress;

    // Establish reprojection transformer.
    psWarpOptions->pTransformerArg = GDALCreateGenImgProjTransformer( hSrcDS, NULL, hDstDS, NULL, FALSE, 0.0, 1 );
    psWarpOptions->pfnTransformer = GDALGenImgProjTransform;

    // Initialize and execute the warp operation.
    GDALWarpOperation oOperation;
    oOperation.Initialize( psWarpOptions );
    CPLErr warpError = oOperation.ChunkAndWarpImage( 0, 0, GDALGetRasterXSize( hDstDS ), GDALGetRasterYSize( hDstDS ) );
    CPLAssert( warpError == CE_None );

    GDALDestroyGenImgProjTransformer( psWarpOptions->pTransformerArg );
    GDALDestroyWarpOptions( psWarpOptions );
    GDALClose( hDstDS );
    GDALClose( hSrcDS );

    WarpResultC* warpResultC = [WarpResultC new];
    warpResultC.geoTransformValues = @[@(adfDstGeoTransform[0]), @(adfDstGeoTransform[1]), @(adfDstGeoTransform[2]), @(adfDstGeoTransform[3]), @(adfDstGeoTransform[4]), @(adfDstGeoTransform[5])];
    warpResultC.newX = nPixels;
    warpResultC.newY = nLines;

    return warpResultC;
}

A: You do this by using GDALCreateGenImgProjTransformer. From documentation:
Create a transformer that maps from source pixel/line coordinates to destination georeferenced coordinates (not destination pixel line).  We do that by omitting the destination dataset handle (setting it to NULL).
Other related info for your task from gdal_alg.h:
Create image to image transformer.
This function creates a transformation object that maps from pixel/line coordinates on one image to pixel/line coordinates on another image. The images may potentially be georeferenced in different coordinate systems, and may used GCPs to map between their pixel/line coordinates and georeferenced coordinates (as opposed to the default assumption that their geotransform should be used).
This transformer potentially performs three concatenated transformations.
The first stage is from source image pixel/line coordinates to source image georeferenced coordinates, and may be done using the geotransform, or if not defined using a polynomial model derived from GCPs. If GCPs are used this stage is accomplished using GDALGCPTransform().
The second stage is to change projections from the source coordinate system to the destination coordinate system, assuming they differ. This is accomplished internally using GDALReprojectionTransform().
The third stage is converting from destination image georeferenced coordinates to destination image coordinates. This is done using the destination image geotransform, or if not available, using a polynomial model derived from GCPs. If GCPs are used this stage is accomplished using GDALGCPTransform(). This stage is skipped if hDstDS is NULL when the transformation is created.


text:
Q: How to stack two models to create a new model in TensorFlow? I am preparing two models (one is a subset of another).
input_shape = (480, 800, 3)
conv_layer = Conv2D(filters=3, kernel_size=5, strides=(1, 1), padding="same")

# The outputs of the conv layer match the inputs of model_1
model_1 = tf.keras.applications.MobileNetV3Small(input_shape)
model_2 = conv_layer + model_1  # I need help with this line

I would like to create the model_2 such that it has an additional Conv2D layer. The parameters of the conv_layer ensure that the input size is the same as its output. Therefore, it should be possible to stack conv_layer and model_1 to generate model_2.
I was thinking of creating a model with only the conv_layer, like:
conv_model = Sequential([
               Input(shape=input_shape),
               Conv2D(filters=3, kernel_size=5, strides=(1, 1), padding="same")
             ])

In this case, I will have to stack two models conv_model and model_1 to create model_2.
I am not sure how to do either of the two, to achieve what I need.
Edit: Fixed the padding in conv_layer to ensure the input size are the same.

A: You could simply add model_1 to Sequential. Also please note that the outputs of the conv layer don't match the inputs of model_1 - you need to use padding="same" for that:
import tensorflow as tf
import numpy as np

input_shape = (480, 800, 3)
conv_layer = tf.keras.layers.Conv2D(filters=3, kernel_size=5, strides=(1, 1), padding="same")
model_1 = tf.keras.applications.MobileNetV3Small(input_shape)
model_2 = tf.keras.Sequential([
    tf.keras.layers.InputLayer(input_shape=input_shape),
    conv_layer,
    model_1
])
# let's test that everything works on random data
model_2.predict(np.random.random((1, 480, 800, 3)))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to enclose a text in box in itextpdf (while generating pdfs) I have to display a normal text and then the next following text should be inclosed in a box. how can i do this in itextpdf. is there an easy way.
Example
Name: MY NAME
In the above MY NAME should be inclosed in a box.

A: If by "box" you mean a colored background, then you can use the setBackground() method:
Chunk chunk = new Chunk("MY NAME");
chunk.setBackground(BaseColor.RED);

You can add 4 parameters to extend the rectangle to the left, bottom, right and top as the API documentation indicates.
If by "box" you mean a rectangle (without background color), you can use a generic tag event. The MovieYears example shows you how to add a film strip or an ellipse to certain chunks. The result is shown here. The years are put in a small box that looks like pellicule. The IMDB links are put in a blue ellipse.


text:
Q: Hosted asp.net application DirectoryNotFoundException I have an application running on my local server. The application runs locally without any error. But, when I host the application in the Heroku. It produces the error as:
DirectoryNotFoundException: Could not find a part of the path'/app/heroku_output/EmailTemplate/EmailConfirm.html'.

I have been trying to read the file using the below code:
private const string templatePath = @"EmailTemplate/{0}.html";

private string GetEmailBody(string templateName)
{
    var body = File.ReadAllText(string.Format(templatePath, templateName));
    return body;
}

The folder EmailTemplate is in my root directory as shown in the figure.

That folder has also been uploaded to Github and hosted properly in the Heroku. But the application is looking at the file in the wrong project directory i.e in (/app/heroku_output).
What am I missing in my code? How do I approach to read those directories?
After looking for all the deployed files,

A: You attempt to read a file. Reading files is possible within the wwwroot folder. So move your templates there. To access the wwwroot folder use the WebRootPath property from object injected as IWebHostEnvironment
public class EmailTemplateGenerator
{
    private IWebHostEnvironment _env;
    public EmailTemplateGenerator(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void GetEmailBody(string templateName)
    {
        var template = File.OpenRead(Path.Combine(_env.WebRootPath, $"EmailTemplate/{templateName}.html")
    }
}

A: Try following:
In Visual Studio
If you are using Visual Studio to publish, right click each of those files under "EmailTemplate" folder and select "Properties" and set value of "Copy to Output Directory" to "Copy Always". This will make Visual Studio to publish these files to hosted environment. If you are using different application to publish files just make sure "EmailTemplate" folder is published to hosted environment.
In Code
To be on the safe side always access your files through base URL. Example is given below.
//private const string templatePath = @"EmailTemplate/{0}.html";
private const string templatePath = @"EmailTemplate\\{0}.html";

private string GetEmailBody(string templateName)
{
    //var body = File.ReadAllText(string.Format(templatePath, templateName));
    string baseURL = AppDomain.CurrentDomain.BaseDirectory;
    var body = File.ReadAllText(string.Format(baseURL + "\\" + templatePath, templateName));
    return body;
}


text:
Q: How to jump to counterpart definition of current method in Xcode4 with shortcut key? If a class defined as like this,
// A.h
@interface A
- (void)m1;  // I want to jumpt to here directly.
@end

// A.m
@implementation
- (void)m1
{
  // Caret here.
}
@end

I editor caret is places in method implementation body, is there a way to jump to it's definition directly with shortcut key? I can switch to header by pressing CMD + CTRL + UP, however jumped position is not where I want.

A: Edit: Just found it, Command-click on the function name.
Edit2: When I press command the function name turns into a link like the picture below:

Clicking on it takes you to the definition and vice versa.
But since you're looking for a shortcut, CMD + CTRL + D takes you to the definition file and back. You have to put your cursor in the function name though.
Later Edit: Here's a complete list of Xcode 4 keyboard shortcuts.


text:
Q: having close button stick to upper right of video I have a video playing full screen when you first go to my page. I want to have a close button on the upper right corner but I can only keep it on the upper right of the window not the actual video
JSFIDDLE

   <video  width="100%" height="100%" autoplay>
   <source src="aa.ogg" type="video/ogg">
   <source src="aa.mp4" type="video/mp4">
   <source src="aa.webm" type="video/webm">
   <object data="aa.mp4"  width="100%" height="100%">
   <embed  width="100%" height="100%" src="movie.swf">
  </object>
 </video>

My CSS
#vid {
 background-color: black;
 clear: both;
 float: left;
 height: 100%;
 list-style: none outside none;
 position: relative;
 width: 100%;
 z-index: 900;
}

#vid .close_vid {
 background: url(icons/zoom-on.png) no-repeat;
 top: 6px;
 cursor: pointer;
 height: 290px;
 opacity: 1;
 position: absolute;
 width: 29px;
 z-index: 999;
 right: 5px;
}

A: #vid .close_vid {
    position: relative;
}


text:
Q: How to test equality of a decimal with stretchr/testify? I'm having trouble running a unit test to check if a decimal value is what I've expected. This is what I've tried:
func Test_example(t *testing.T) {
    t.Run("test if two decimals are equal", func(t *testing.T) {
        sum_amount := decimal.NewFromFloat(1000.00)
                          .Add(decimal.NewFromFloat(5000.00))

        require.Equal(t, decimal.NewFromFloat32(6000.00), sum_amount))
    })
}

As you can see the sum_amount is a decimal. However comparing the two in the test case work out slightly differently with exponents etc.
How do I properly assert that these values are equal with stretchr/testify?
E.g. here's the diff:
Diff:
--- Expected
+++ Actual
@@ -4,6 +4,6 @@
    abs: (big.nat) (len=1) {
-   (big.Word) 6
+   (big.Word) 6000
      }
    }),
- exp: (int32) 3
+ exp: (int32) 0
  }

A: You can make use of decimal.Equal so that values can be compared using the library to return a bool and then just test if that result is true.
Like this:
require.Equal(t, decimal.NewFromFloat(6000.00).Equal(sum_amount), true)

Also instead of comparing two values for equality you can just check that the result is true using require.True
This is the end result:
require.True(t, decimal.NewFromFloat(6000.00).Equal(sum_amount))


text:
Q: Assign a DateTime to Nullable in F# I have some F# code where I need to update a field in a database record. I am using the Type Provider for SQL.  The table has a nullable datevalue field.  When I try to update the value of the date field to DateTime.UtcNow the compiler complains that "This expression was expected to have type Nullable<DateTime> but here has type DateTime".  How do I convert/cast from DateTime to Nullable<DateTime>.
My code currently looks something like follows:
for queryItem in queryResult do
    queryItem.CurrentDate <-  DateTime.UtcNow  // This gives compiler error as described above

Regards

A: The comment by John Palmer above links to the solution.  One needs to use the System.Nullable constructor i.e.
queryItem.CurrentDate <- System.Nullable DateTime.UtcNow


text:
Q: Selecting id's from a huge database I have a database with over 3,000,000 rows, each has an id and xml field with varchar(6000).
If I do SELECT id FROM bigtable it takes +- 2 minutes to complete. Is there any way to get this in 30 seconds?

A: Build clustered index on id column
See http://msdn.microsoft.com/en-us/library/ms186342.aspx

A: You could apply indexes to your tables. In your case a clustered index.
Clustered indexes:
http://msdn.microsoft.com/en-gb/library/aa933131(v=sql.80).aspx
I would also suggest filtering your query so it doesn't return all 3 million rows each time, this can be done by using TOP or WHERE.
TOP:
SELECT TOP 1000 ID
FROM bigtable

WHERE:
SELECT ID FROM
bigtable
WHERE id IN (1,2,3,4,5)

A: First of all, 3 milion records dont make a table 'Huge'.
To optimize your query, you should do the following.

*

*Filter your query, why do you need to get ALL your IDs?

*Create clustered index for the ID column to get a smaller lookup table to search first before pointing to the selected row.

Helpful threads, here and here

A: Okay, why are you retuning all the Ids to the client?
Even if your table has no clustered index (which I doubt), the vast majority of you processing time will be client-side, transferring the Id values over the network and displaying them on the screen.
Querying for all values rather defeats the point of having a query engine.

The only reason I can think of (perhaps I lack imagination) for getting all the Ids is some sort of misguided caching.
If you want to know many you have do
SELECT count(*) FROM [bigtable]

If you want to know if an Id exists do
SELECT count([Id[) FROM [bigtable] WHERE [Id] = 1 /* or some other Id */

This will return 1 row with a 1 or 0 indicating existence of the specified Id.
Both these queries will benefit massively from a clustered index on Id and will return minimal data with maximal information.
Both of these queries will return in less than 30 seconds, and in less than 30 milliseconds if you have a clustered index on Id
Selecting all the Ids will provide no more useful information than these queries and all it will achieve is a workout for you network and client.

A: You could index your table for better performance.
There are additional options as well which you could use to imrpove performance like partion feature.


text:
Q: String was not recognized as a valid DateTime phpMyAdmin Worked with phpMyAdmin, and wanted to update data from C#.
I had "yyyy-MM-dd" format for column dateBuy in phpMyAdmin.
To display it, I changed the format to "dd/MM/yyyy" in C#.
This is the code: (I don't have problem with this code)
string dateBuy = dr.GetValue(1).ToString();
DateTime time = DateTime.Parse(dateBuy);
dateBuy = time.ToString("dd/MM/yyyy");

To update database, I wanted to change the format back to "yyyy-MM-dd". But, I had an error: "String was not recognized as a valid DateTime".
This is the error parts of my code:
string dateBuy2 = txtDateBuy.Text;
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();

Did I make mistake in the DateTime syntax? Thanks for your help.

A: [Since it is not good if we continue in the comments (the comments will be long), I will just put up what I think as a solution here]
To format dateBuy to the format that you want, you should also put the string format in the ToString()
That is, instead of
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();

put
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString("yyyy-MM-dd");

Otherwise, it is possible for the ToString() to produce something like "2015-10-16 12:00:00 AM" instead of "2015-10-16"
However, since you use ParseExact, the input for the dateBuy2 must also be in the format of "yyyy-MM-dd" which defeats the purpose. You may consider using DateTimePicker such that you can control the input format.
Alternatively, you can use DateTime.Parse or TryParse (as suggested by Martheen) instead, something like this
try {
    DateTime dt = DateTime.Parse(txtDateBuy.Text);
    dateBuy = dt.ToString("yyyy-MM-dd");
} catch (Exception exc) {
    //wrong format, do something to tell the user
}

If input has to be in the TextBox you better put try-catch to prevent your program crash for taking wrong-formatted input if you use Parse.
Where as if you use TryParseyou can put it in if-else block statement instead
DateTime dt;
if (DateTime.TryParse(txtDateBuy.Text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt)) {
    //correct format, do something using dt
} else {
    //incorrect format, warns the user
}

To get CultureInfo enum you need to add reference to System.Globalization
[Edited after suggestion given by Mr. Soner Gonul]


text:
Q: Adding another HardDisk to my server I have a ubuntu server and I am planning to add another harddisk to it.
Currently installed harddisk is iSCSI drive and I can add new SATA2 harddisk using NAS or SAS.
I lack knowledge of linux in windows when a new harddisk is installed it is like a different partition on linux how would it work a partition or add up to current harddisk space automatically? wherein I can continue storing files in /var/www/data
Thank You.

A: On Unix systems, which includes Linux, partitions are physical space that you dedicate to a path. If you had only one partition, it would necessarily be allocated to '/', since this partition is mandatory.
If you wish to allocate physical space to /var/www/data using a specific partition, here is what you should do:

*

*Create a new partition (on the same disk or another disk) and format it ;

*Stop the services using the directory you wish to use as a mount point ;

*Move the data in this directory to another place that has enough space ;

*Find the identifier of your new partition ;

*Mount the new partition on the path you wish to use ;

*Put your data back in the directory.

*Add the mount configuration in /etc/fstab to make sure your partition is mounted at startup.

Step 3 is important. If you don't do it, this is what will happen:

*

*Your data is stored on the original partition (let's say it's /dev/sda1 for example) ;

*You mount the new partition on top of the directory (let's imagine this is /dev/sdb2 for example) ;

*You see the directory being empty, because /dev/sdb2 doesn't contain anything. The data are still stored in /dev/sda1, but you can't see them or remove them anymore, unless you unmount /dev/sdb2 first.

This is why it's important to clean the directory before you mount a partition on it.
You can find more informations on using partitions on Linux on this page.


text:
Q: I'm running Ubuntu on my Nexus 7, do I have access to the same packages as if I'm running Ubuntu on my Desktop? I noticed that some packages are not available on my Nexus 7 when browsing the Software Center or using "apt-cache search". Can anyone explain?

A: No Not Exactly, The Nexus 7 is an ARM based platform, therefore uses a different package archive than your common x86 Desktop. If the desired package is not available for ARM, then it will not be available to download.
As there are some Nexus 7 specific packages. These packages are found in the nexus 7 ppa (ppa:ubuntu-nexus7/ppa).  The Nexus 7 PPA is enabled by default when you install. We are currently in the process of migrating all our changes upstream into Raring Ringtail (13.04). When that switch occurs, most updates will come from the main Raring repositories.

A: The nexus 7 uses an arm CPU. Anything that doesn't work on an arm CPU will not be available.


text:
Q: Minio - bucket usage count not updating I'm running MinIO via Docker (version 2022-04-16, so it could do with being updated). I have a handful of buckets used to store backups. Each bucket containers a handful of date stamped folders, each with 1 or 2 large (10GB+) files inside.
In the MinIO Console, the bucket usage is showing what I think may be peak usage. Deleting data via the Console doesn't seem to reduce the usage figures at all. One bucket is now empty, but still showing 2.2TiB of usage.
Is there a way to update these counts? Is there a cron task or similar that I'm missing?


text:
Q: How to generate all valid numeric expressions? Assume I have operators:  'add' 'sub' 'mul' 'div'(these have two parameters) and 'ifelse'(this should have three parameters)
And some variables: a, b, c, d
And some constants: 1,2,3,4
how can i generate all valid expressions on a given depth n?(time sensitive)
ps. valid expression, for example:  div(sub(add(a, b), 3), div(a, b)) is valid, and its depth is 3.

A: You can use recursion with a generator:
import itertools as it
params = {'add':2, 'mul':2, 'sub':2, 'div':2, 'ifelse':3}
def get_exp(d, f = None):
  if d:
    for i in (params if not f else [f]):
       for k in it.product(*([[*range(1, 5), 'a', 'b', 'c', 'd', *params]]*params[i])):
          for l in it.product(*[[a] if a not in params else get_exp(d-1, a) for a in k]):
              yield f'{i}({", ".join(map(str, l))})'

stream = get_exp(3)
for _ in range(100):
   print(next(stream))


text:
Q: Is there a BeforeCheck for WPF checkboxes? Some of the checkboxes on my form should not be able to be checked/unchecked by users. Is there a way for me to cancel the event before the checbox's Check event is triggered?
in winForms it was easy, just
public void cb_BeforeChecked(object sender, EventArgs e){
    e.Handled = true;
}

but I cannot find anything like this in WPF...I figure you can probably do it, just need to do something fancy..
Thanks!

A: You can set IsHitTestVisible="False" to make it not respond to user clicks.  Otherwise you can bind it to a command if viewmodel logic determines whether it is clickable.
<Grid>
    <CheckBox IsHitTestVisible="False" Content="I cannot be clicked at all"/>
<CheckBox Command="{Binding DoSomethingCommand}" Content="I can be clicked if DoSomethingCanExecute returns true."/>
</Grid>

In your DataContext (Viewmodel or otherwise):
    RelayCommand _DoSomethingCommand = null;

    public ICommand DoSomethingCommand
    {
        get
        {
            if (_DoSomethingCommand== null)
            {
                _DoSomethingCommand= new RelayCommand(
                    param => DoSomething(),
                    param => DoSomethingCanExecute
                    );
            }
            return _DoSomethingCommand;
        }
    }

    public bool DoSomethingCanExecute
    {
        get
        {
            return CheckboxShouldBeEnabled();
        }
    }

    public void DoSomething()
    {
        //Checkbox has been clicked
    }

A: Why not just set IsEnabled="False"?

A: This might be a bit of an overkill, but you could sub-class CheckBox and then override the OnClick() method.

A: Only setting IsHitTestVisible="False" just takes care of the Mouse, the users can still use the KeyBoard to tab to the CheckBox and change the value.
You should set both IsHitTestVisible="False" and Focusable="False" to disable the KeyBoard as well

A: You can have the check box disabled, and associate a style with the disabled check box, if the disabled look is a problem. As its already pointed in the previous posts, its good to have different looks for different states.


text:
Q: how to distinguish function names in C++ if I have same function name but one is C++ and another is C suppose I have a class with one of the method member name is close,
and inside the class, I'm using C function  to open and close file
thus, I will have two completely different function with the same name, but one is C and another is C++.
Thus, when I call close, seems compiler is confused
    s = socket(PF_INET, SOCK_DGRAM, 0);
    close(s)

how to solve this issue? Thanks

A: Your member function:
close(s)

Function in global namespace:
::close(s)

A: Use scope resolution operator(::) for global function.

A: the compiler usually change the name of functions you define to some unique function name. so if you use function overriding the compiler has its unique name for every function. This is done with the help of name mangling in C++.
You should read the concept of name mangling that can help you solve the issue.


text:
Q: Pytest how to specify python version per test function I'm running some tests and one of them compares an exception with it's message, it looks like this, BaseCallback is just a class with abstract methods from abc, I'm testing that there is an error if the methods are not defined using inheritance, intentionally I miss the method __call__ that is mandatory by the base class
from base import BaseCallback

import pytest

def test_base_callback_call():
    class MyDummyCallback(BaseCallback):
        def __init__(self, metric):
            self.metric = metric

        def on_step(self, record=None, logbook=None, estimator=None):
            print(record)

    with pytest.raises(Exception) as excinfo:
        callback = MyDummyCallback(metric="fitness")

    assert (
        str(excinfo.value) == "Can't instantiate abstract class MyDummyCallback with abstract methods __call__ "
    )

The problem is that I'm testing several python versions at the same time, it works on
python 3.6, 3.7 and 3.8 but in python 3.9 the assertion message changes from
"Can't instantiate abstract class MyDummyCallback with abstract methods call "
to "Can't instantiate abstract class MyDummyCallback with abstract method call "
So it makes my test fail due that missing S
Is there a way that I set the valid python versions in this function (say from 3.6 to 3.8) and create another test for python 3.9? Or what would be the suggested way to handle this kind of changes?
I made a turnaround by checking by 1 of the 2 messages, if at least 1 is present the test pass, but it feels kinda odd

A: pytest allows you to conditionally skip tests by using the skipif decorator.
@pytest.mark.skipif(sys.version_info >= (3, 9))
def test_base_callback_call():
   ...

https://docs.pytest.org/en/6.2.x/skipping.html#id1


text:
Q: Using Promises to connect React Components I came up with solution to a React problem and want to see what people think.
The Problem: I have a really big form component with lots of subforms that can each be expanded and minimized. The parent form component is already managing a ton of state because all of the sub forms report their input values to it. There is also an "ErrorBubble" component. Whenever the form is validated and there is an error, the ErrorBubble appears and finds the first invalid field in the form and moves to it. The ErrorBubble also has to dynamically update its position as the size of the form changes, which happens if you minimize or expand any of the subforms. So, the problem is, how do you get each of the subForms to communicate to the ErrorBox that it needs to reposition?
The traditional solution: Just have the parent form component manage all the state. Each subform reports any change in its expanded state to the parent component, which causes a re-render of everything including the ErrorBubble.
Cons: Parent component already has a ton of methods and state it is managing, I don't want to add more. Forces a re-render of the whole parent form component
The Redux Solution: Have each subform dispatch a redux action and the ErrorBubble connected to the Redux store.
Cons: Lot of boilerplate to create. Have to create a reducer and a piece of redux store just for this. Have to design the redux actions. Have to connect ErrorBubble to redux. Also updating the redux store on every resize of the subforms may be inefficient?
My Solution: I have a DeferredTask custom object helper. I create an instance of it in the constructor of the parent form component and save it as state. Here is the custom object:
export class DeferredTask {
  constructor () {
    this.promise = new Promise((resolve, reject) => {

      this.resolve = resolve
      this.reject = reject

      this.reset = function () {
        this.promise = new Promise((resolve, reject) => {

          this.resolve = resolve
          this.reject = reject

        })
      }
    })
  }
}

I then passed this.state.deferredTask onto all the subforms and the ErrorBubble as a prop.
Whenever the ErrorBubble mounts, it runs a method that listens for this deferredTask to resolve, and when it unmounts it rejects the task to close it out so it doesn't remain perpetually pending:
componentDidMount() {
  this.repositionErrorBubble()
  this.deferredTask()
}

deferredTask = () => {
  this.props.deferredTask.reset()
  this.props.deferredTask.promise
    .then(()=>{
      if(this._calledComponentWillUnmount) {
        return
      }
      this.repositionErrorBubble()
      this.deferredTask()
    })
}

componentWillUnmount () {
  this.props.deferredTask.reject()
}

Each of the subforms have:
componentDidUpdate () {
  this.props.deferredTask.resolve()
}

Now every time any subforms updates they resolve the promise and the ErrorBubble runs its then(). It needs to check if the ErrorBubble component is scheduled to unmount because you cant update state of an unmounting component. Otherwise, it runs the code to reposition the ErrorBubble then resets the promise and starts listening to it again.
Pros: Only create one piece of state and pass down one prop from parent form component. Pretty minimal code surface area connecting these components. Don't have to go through the regular prop channels to update. componentWillReceiveProps is already bloated with a ton of other checks.
Its like a quasi pub-sub pattern but neater?
What do you guys think? Is this a react anti-pattern because there is data being passed horizontally and not vertically? Keep in mind the deferredTask object is still available as state in the parent component and is being passed down... Does that make it any better?
Are there pitfalls for using asynchronous promises? Could it bite me in the butt? Since the only things triggering the resolves are successive user interactions and the promise is reset after each interaction, it shouldn't ever cause any confusion which promise is resolving should it? So far i've tried spamming the subform resize and it has not caused any problems.
Is there a better way to do this that works with React?


text:
Q: Event-log messages gets expanded when unhandled exceptions are handled by ASP.NET If I throw an unhandled exception from ASP.NET, a warning is added to the eventlog (as expected).
But if the message in the exception contains a %, the message in the eventlog gets garbled:
If the Message was
Could not find foo%20bar

the eventlog will read
Could not find foohttp://localhost/testpage.aspxbar

Other numeric values after the % will be converted to other strings.
It looks like the message gets passed through a printf-statement somewhere on the way.
Is this per design? Is there a way to avoid this (besides making sure that exceptions are handled)?
EDIT:
If I look at the XML-view under details in the eventlog, I see:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
  <Provider Name="ASP.NET 2.0.50727.0" />
  <EventID Qualifiers="32768">1309</EventID>
  <Level>3</Level>
  <Task>3</Task>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2009-06-26T11:10:09.000Z" />
  <EventRecordID>130253</EventRecordID>
  <Channel>Application</Channel>
  <Computer>XXX</Computer>
  <Security />
</System>
<EventData>
  <Data>3005</Data>
  <Data>An unhandled exception has occurred.</Data>
  <Data>26-06-2009 13:10:09</Data>
  <Data>26-06-2009 11:10:09</Data>
  <Data>525e4e8df6ec432d9a9b9b77e9ded580</Data>
  <Data>6</Data>
  <Data>1</Data>
  <Data>0</Data>
  <Data>ecd2c9a5-1-128904882075773124</Data>
  <Data>Full</Data>
  <Data>/WebSite1</Data>
  <Data>C:\Users\XXX\Documents\Visual Studio 2008\WebSites\WebSite1\</Data>
  <Data>XXX</Data>
  <Data />
  <Data>6404</Data>
  <Data>WebDev.WebServer.EXE</Data>
  <Data>XXX</Data>
  <Data>Exception</Data>
  <Data>Foo%20Bar</Data>
  <Data>http://localhost:6594/WebSite1/Default.aspx</Data>
  <Data>/WebSite1/Default.aspx</Data>
  <Data>127.0.0.1</Data>
  <Data>XXX</Data>
  <Data>True</Data>
  <Data>NTLM</Data>
  <Data>XXX</Data>
  <Data>4</Data>
  <Data>XXX</Data>
  <Data>False</Data>
  <Data>at _Default.Page_Load(Object sender, EventArgs e) at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)</Data>
</EventData>
</Event>

This looks fine. So it looks like the problem might be in the Event Viewer. What logic converts the XML event data into the formatted data under General?

A: Unless someone else knows otherwise, I'll have to say that this sounds like a bug.
If so, then please report this at http://connect.microsoft.com/visualstudio/. Please search first to see if it's already been reported. Then, edit your question to include the URL of the bug report. That way, anyone reading this can vote on how important they feel this bug is to fix.


text:
Q: Display error message if no result found This is the controller snippet. Somehow it doesn't work. I have checked the results and it is null, but the error is not showing. I also have apex:messages in my VisualForce page.
public PageReference doSearch() {
    results =  [SELECT Name, Employee_No__c, Email, ESS_User__c, Phone FROM Contact WHERE Employee_No__c =:searchEmpNo AND SSS_No__c =:searchEmpSSSNo];
    if (results == null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'No Results Found'));
        }
        return null;
    }

A: If you are using reRender, then the issue is here
if (results == null){

change this to
if (results.isEmpty())

, because query will return empty list.

A: try this
public PageReference doSearch() {
    Integer counter = 0;
    counter =  [Select count() FROM Contact WHERE Employee_No__c =:searchEmpNo AND SSS_No__c =:searchEmpSSSNo ];
    if(counter == 0){
           ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'No Results Found'));

         }
          return null;
   }


text:
Q: Normal vector of hypersurface in Schwarzshild spacetime I've read that the following hypersurface is a null surface which means that the normal four-vector has a length of 0. I would however like to confirm this myself.
$$
2 M G \ln \left|\frac{r}{2 M G}-1\right| + t+r= B
$$
where $B$ is a constant and the surface is located in Schwarzshild spacetime.
How do I compute the normal four-vector and its length?
I suspect I should use the gradient to get a normal four-vector but what does the gradient look like here? Is it made up of partial derivatives or covariant derivatives?
Update: use the metric tensor?
It seems like the covariant derivative (which is used to get the four-gradient) reduces to the normal partial derivative in this case since it is a scalar function. Wikipedia says that

In GR, one must use the more general metric tensor $g^{\alpha \beta}$, and the tensor covariant derivative
(en.wikipedia.org)

A: Your surface is defined implicitly by the equation $F(t,r,\theta,\phi) = B$.  The natural object which defines the orientation of the surface is not a vector but rather a covector $n_\mu$, with components
$$n_\mu = \partial_\mu F$$
The surface is null if $g^{\mu\nu} n_\mu n_\nu = 0$.  If you insist on talking about vectors, then you can "raise the index" on $n_\mu$ to find its vector partner given by
$$\tilde n^\mu = g^{\mu \nu} n_\nu = g^{\mu\nu} \partial_\nu F$$
The surface is then null if $g_{\mu\nu} \tilde n^\mu \tilde n^\nu = 0$.  Of course, going this route is pointless, because
$$g_{\mu\nu} \tilde n^\mu \tilde n^\nu = g_{\mu\nu} g^{\mu\alpha} n_\alpha g^{\nu\beta} n_\beta = \delta^\alpha_\nu g^{\nu \beta} n_\alpha n_\beta = g^{\alpha \beta}n_\alpha n_\beta$$
so converting $n_\mu$ to a vector first and then computing the inner product from there amounts to just circling the block a few times.


text:
Q: Django CSRF cookie not set correctly Update 7-18:
Here is my nginx config for the proxy server:
server {
    listen 80;
    server_name blah.com; # the blah is intentional

    access_log /home/cheng/logs/access.log;
    error_log /home/cheng/logs/error.log;

    location / {
        proxy_pass http://127.0.0.1:8001;
    }

    location /static {
        alias /home/cheng/diandi/staticfiles;
    }

    location /images {
        alias /home/cheng/diandi/images;
    }

    client_max_body_size 10M;
}

Here is nginx.conf:
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip_disable "msie6";

        # Enable Gzip compressed.
        gzip on;

        # Enable compression both for HTTP/1.0 and HTTP/1.1.
        gzip_http_version  1.1;

        # Compression level (1-9).
        # 5 is a perfect compromise between size and cpu usage, offering about
        # 75% reduction for most ascii files (almost identical to level 9).
        gzip_comp_level    5;

        # Don't compress anything that's already small and unlikely to shrink much
        # if at all (the default is 20 bytes, which is bad as that usually leads to
        # larger files after gzipping).
        gzip_min_length    256;

        # Compress data even for clients that are connecting to us via proxies,
        # identified by the "Via" header (required for CloudFront).
        gzip_proxied       any;

        # Tell proxies to cache both the gzipped and regular version of a resource
        # whenever the client's Accept-Encoding capabilities header varies;
        # Avoids the issue where a non-gzip capable client (which is extremely rare
        # today) would display gibberish if their proxy gave them the gzipped version.
        gzip_vary          on;

        # Compress all output labeled with one of the following MIME-types.
        gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/rss+xml
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                application/x-javascript
                font/opentype
                image/svg+xml
                image/x-icon
                text/css
                text/plain
                text/javascript
                text/js
                text/x-component;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

Update 7-15:
When copying code to the linux machines, I simply replaced the original source code file but didn't delete the old .pyc files which I don't think will cause trouble right?

Here is the view code:
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render

def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        next_url = request.POST['next']
        if user is not None:
            if user.is_active:
                login(request, user)
                if next_url:
                    return HttpResponseRedirect(next_url)
                return HttpResponseRedirect(reverse('diandi:list'))
        else:
            form = {'errors': True}
            return render(request, 'registration/login.html', {'form': form})

    else:
        form = {'errors': False}
        return render(request, 'registration/login.html', {'form': form})

I got one of those CSRF cookie not set error from Django, but this is not because I forgot to include the {% csrf_token %} in my template.
Here is what I observed:
Access login page #1 try
Inside the Request Header, the cookie value is:
csrftoken=yNG8ZmSI4tr2xTLoE9bys8JbSuu9SD34;

In the template:
<input type="hidden" name="csrfmiddlewaretoken" value="9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB">

In a cookie plugin that I installed on chrome, the actual csrf cookie value is set to:
9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB

Access login page #2 try:
Inside the Request Header, the cookie value is:
csrftoken=9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB;

In the template:
<input type="hidden" name="csrfmiddlewaretoken" value="Y534sU40S8iTubSVGjjh9KQl0FXesVsC">

In a cookie plugin that I installed on chrome, the actual csrf cookie value is set to:
Y534sU40S8iTubSVGjjh9KQl0FXesVsC

The pattern
As you can see from the examples above, the cookie value inside the Request Header differs from the actual csrfmiddlewaretoken in the form and the actual cookie value being set.
The cookie value of the current request matches the next request header's cookie value.

To help debugging, here is a portion of my `settings.py:
DJANGO_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

THIRD_PARTY_APPS = (
    'compressor',
    'crispy_forms',
    'django_extensions',
    'floppyforms',
    'multiselectfield',
    'admin_highcharts',
)

LOCAL_APPS = (
    'diandi_project',
    'uer_application',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [str(ROOT_DIR.path('templates'))],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

I am using Django 1.9.5 and python 2.7.10.
One "solution"
I have encountered this problem before, I can clear all my browser cookies and the site will function properly. But this problem will eventually come up again, so I am really hoping someone can help me out (I probably just made a really dumb mistake somewhere).
Update
Originally, I thought I made some mistakes while overriding the django.contrib.auth.view page, so I wrote my own login page handler and it still causes the issue.
Here is the core part of my login template:
{% block content %}
...

                <form method="post" action="{% url 'login' %}">
                    {% csrf_token %}

                        username
                        <input type="text" class="form-control" id="id_username" name="username">

                        password
                        <input type="password" class="form-control" id="id_password" name="password">

                    <input type="submit" class="btn btn-default" value="login" />
                    <input type="hidden" id="next" name="next" value="" />
                </form>

...

{% endblock %}

On the Linux machines, I have a nginx server setup as a reverse proxy which direct request on port 80 to 8001, and I am running the server using ./manage runserver localhost:8001 This is the only difference I can think of in terms of setup. Otherwise, all of the source code and settings file are identical.

I started deleting cookies but not all of them, this is what I see before deleting them:

I deleted all the cookies other than djdt and csrftoken, then the page worked. Could the deleted cookies somehow go over some limit which prevent the csrftoken which is further down the list from being set?
Here is the cookie value of the image above in the request header:
Cookie:PSTM=1466561622; BIDUPSID=6D0DDB8084625F2CEB7B9D0F14F93391; BAIDUID=326150BF5A6DFC69B6CFEBD67CA7A18B:FG=1; BDSFRCVID=Fm8sJeC62leqR8bRqWS1u8KOKg9JUZOTH6ao6BQjXAcTew_mbPF_EG0PJOlQpYD-hEb5ogKK0mOTHvbP; H_BDCLCKID_SF=tJPqoCtKtCvbfP0k-tcH244HqxbXq-r8fT7Z0lOnMp05EnnjKl5M3qKOqJraJJ585Gbb5tOhaKj-VDO_e6u-e55LjaRh2PcM2TPXQ458K4__Hn7zep0aqJtpbt-qJjbOfmQBbfoDQCTDfho5b63JyTLqLq5nBT5Ka26WVpQEQM5c8hje-4bMXPkkQN3T-TJQL6RkKTCyyx3cDn3oyToVXp0njGoTqj-eJbA8_CtQbPoHHnvNKCTV-JDthlbLetJyaR3lWCnbWJ5TMCo1bJQCe-DwKJJgJRLOW2Oi0KTFQxccShPC-tP-Ll_qW-Q2LPQfXKjabpQ73l02VhcOhhQ2Wf3DM-oat4RMW20jWl7mWPQDVKcnK4-Xj533DHjP; BDUSS=5TNmRvZnh2eUFXZDA5WXI5UG1HaXYwbzItaWt3SW5adjE1Nn5XbUVoWHZuYXBYQVFBQUFBJCQAAAAAAAAAAAEAAAC0JtydAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO8Qg1fvEINXSU; Hm_lvt_a7708f393bfa27123a1551fef4551f7a=1468229606; Hm_lpvt_a7708f393bfa27123a1551fef4551f7a=1468229739; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; cflag=15%3A3; H_PS_PSSID=1424_20515_13289_20536_20416_19861_14994_11792; csrftoken=xUgSHybzHeIwusN0GvMgB1ATeRrPgcV1

Since the site functions now, all I have are five cookies instead of 14 like the image above:

A: Here is the issue: You cannot have a cookie which key contains either the character '[' or ']'
I discovered the solution following @Todor's link, then I found out about this SO post. Basically there was a bug in python 2.7.x that does not parse cookies with ']' in the value. The bug was fixed in 2.7.10.
I thought it would be good to just confirm this issue. So I dug through all of the cookies and found one with the following key/value:
key: BDRCVFR[feWj1Vr5u3D]
val: I67x6TjHwwYf0

So I inserted the following cookie locally and submitted to the server:
key: test
val: BDRCVFR[feWj1Vr5u3D]

The login page worked, which means 2.7.10 indeed fixed the bug.
But then I realized that the square brackets are actually in the key name not in the value, so I did the following tests:
key: [
val: I67x6TjHwwYf0

and
key:]
val: I67x6TjHwwYf0

Both cookies break the login process and django displays:
CSRF cookie not set

So either django or a python library it relies on cannot parse cookies with square brackets in names properly. If anybody knows where I should submit this bug please let me know (django or python).
I would like to thank everybody who left a comment in the OP: @raphv, @trinchet, @Phillip, @YPCrumble, @PeterBrittain and @Todor. Thank you guys so much for debugging with me!

Update: July 20, 2016
This bug is fixed in Django 1.10, just have to wait for the release
Update: July 19, 2016
I filed a bug report to Django as the result of this post. We will see if it will be fixed in future releases.


text:
Q: How do you run Cleanmgr.exe remotely? I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.
I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.
Any ideas?
( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )
## Starts cleanmgr.exe
Function Start-CleanMGR {
    Write-Host "Please provide your A-Account details to continue with this cleanup."
    $creds = Get-Credential
    Enter-PSSession -ComputerName $computername -Credential $creds
    try {
        $cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
        if ($cleanmgr) {
            Write-Host "Clean Manager ran successfully!                                                                   " -NoNewline -ForegroundColor Green
            Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
        }
    }
    catch [System.Exception] {
        Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
        Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
    }
} Start-CleanMGR

A: I suggest that you use Invoke-Command
Function Start-CleanMGR ($computername, $creds) {
        Invoke-Command -ComputerName $computername -Credential $creds -ScriptBlock {
        try {
            $cleanmgr = Start-Process -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
            if ($cleanmgr) {
                return "Clean Manager ran successfully!"
            }
        }
        catch [System.Exception] {
            return "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:"
        }
    }
}

Start-CleanMGR -computername "remotehost" -creds (Get-Credential)

A: PowerShell always runs in the user context of the user who started the session. This is by design.
You can not run a GUI based application remotely using PowerShell. It is a Windows security boundary.
To run GUI apps, someone must be logged on, and you cannot use PowerShell to run code as the logged-on user.
You are also prompting for info, so, someone must be logged on.
If you are expecting a user to prived info, then you need to:

*

*Create the script

*Deploy the script to the user's machine or a files share from wich it
can be ran

*Tell the user how to do it or create a batch file they would double
click to run the PowerShell script

Or
Set the script to run as a scheduled task at log on or at some point during the day, as the user credentials.
Variables have the scope and you cannot use local variables in a remote context unless they are scoped for that.

About Remote Variables
Using local variables
You can use local variables in remote commands, but the variable must
  be defined in the local session.
Beginning in PowerShell 3.0, you can use the Using scope modifier to
  identify a local variable in a remote command.
The syntax of Using is as follows:

$Using:<VariableName>

Still, the remote variable is not something you will do in your use case since you cannot do what you are after natively with PowerShell. You'll need a 3rdP tool like MS SysInternals PSExec to run code remotely as the logged-on user.

Using PsExec
Usage: psexec [\computer[,computer2[,...] | @file]][-u user [-p
  psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c
  executable [-f|-v]][-w directory][-d][-][-a n,n,...] cmd
  [arguments]
-i    Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the
  process runs in the console session.
-u    Specifies optional user name for login to remote computer.

A: As long as you execute cleanmgr.exe under a user account that has local admin rights, everything will work. Running cleanmgr.exe under the SYSTEM account, E.G. running from the Run Script Tool in SCCM/MECM will not work unless the script first opens a separate shell (DOS/PS) under a user that has local admin rights...even the cleanmgr.exe /verylowdisk will not run under the SYSTEM account.


text:
Q: Do I need onlyamsmath when using nag? I already read questions about recommended packages, and they often have the advice for
\RequirePackage[l2tabu, orthodox]{nag}

and
\usepackage[all, warning]{onlyamsmath}

I use nag for quite some time now and am unsure if I still need onlyamsmath. My question: as far as I understand, nag already does everything and more that onlyamsmath is doing when it comes to math environments (warn about "bad" math environments), is this correct?
So, does onlyamsmath bring any further advantage if I already use nag? I don't need the error functionality of onlyamsmath, only the warnings.

A: OK, I found some time to test this out. I tested everything that onlyamsmath mentioned in its documentation, assuming the documentation is complete. The following code:
\RequirePackage[l2tabu, orthodox]{nag}
\documentclass[fleqn]{scrreprt}

%\usepackage[all, warning]{onlyamsmath}

\begin{document}

$$a = b$$

\begin{eqnarray}
  a = b
\label{eq:foo1}
\end{eqnarray}

\begin{eqnarray*}
  a = b
\label{eq:foo2}
\end{eqnarray*}

\begin{displaymath}
  a = b
\end{displaymath}

\end{document}

Generates these warnings:
Package nag Warning: $$...$$ is obsolete.
(nag)                Use \[...\] et al. instead on input line 8.

Package nag Warning: Environment eqnarray is obsolete.
(nag)                Use amsmath's align instead on input line 10.

Package nag Warning: Environment eqnarray is obsolete.
(nag)                Use amsmath's align instead on input line 15.

And now commenting out nag and commenting in onlyamsmath produces these warnings:
Package onlyamsmath Warning: Environment $$ $$ used, please use
(onlyamsmath)                only the environments provided by the amsmath
(onlyamsmath)                package on input line 8.

Package onlyamsmath Warning: Environment eqnarray or eqnarray* used, please use
(onlyamsmath)                only the environments provided by the amsmath
(onlyamsmath)                package on input line 10.

Package onlyamsmath Warning: Environment eqnarray or eqnarray* used, please use
(onlyamsmath)                only the environments provided by the amsmath
(onlyamsmath)                package on input line 15.

Package onlyamsmath Warning: Environment displaymath used, please use
(onlyamsmath)                only the environments provided by the amsmath
(onlyamsmath)                package on input line 20.

If you use both at the same time, only onlyamsmath will complain about $$...$$, but nag will not. eqnarray will be warned about by both packages at the same time. displaymath is only complained about by onlyamsmath in all cases.
Conclusion: Yes, onlyamsmath does detect something that nag won't detect (displaymath).


text:
Q: Testing the assumptions of a linear regression model I am building a model for predicting airline prices. I have 19 relevant predictors and and 114000 observations. I am getting an $R^2$ predicted of 95.87 (Minitab displays $R^2$ predicted after applying the PRESS Statistic for cross- validation).
Do I need to test for the five assumptions of a linear regression model    before running Multiple Linear regression in Minitab ?
The five assumptions are the following
i.e

*

*Linear relationship

*Multivariate normality

*No or little multicollinearity

*No auto-correlation

*Homoscedasticity

A: The text book answer is that you should always check the assumptions before fitting in model.
In practice, most people just apply the model, usually not even aware of the assumptions.
The reason to applying the model directly is thinking that in the worse case the model won't fit.
It is true that your test set/cross validation functions a a safety belt that will alert if the model won't fit.
In many cases validating the assumptions is hard so "giving it a try" looks like a good method.
Yet, one should note that giving it a try might be misleading.
Let's say that you tried your model and it didn't fit.
It might be since your data represent a relation that is not linear but quadratic. If you validated the assumptions, you could have find it add a quadratic term and get a good model. Without validating you will not go in a fruitful direction.
Even when your model works. you might get into problems.
It is way to common to assume (without any validation) that parameter weight indicates importance and causality. If you have collinearity than a parameter with a positive influence might get a negative weight.
Here the path of wrong assumptions might send you in the opposite direction.
On top of all that, you cannot "give a try" to all the options. If you check the assumptions you can learn which directions a more promising and invest your time there.


text:
Q: Preposition in and on regarding clothes Hi I tried to look for a grammatical explanation for the usage of "in" and "on" in this context (please see examples below) but I couldn't find any. Why is
 sentence A and C are correct but sentence B and D are wrong?

A) The girl in the red dress.                                                         B) The girl on the red dress.                                                           C) The girl with the red dress on.                                                                D) The girl with the red dress in.

A: To have an article of clothing on means to be wearing it.
This pattern

The {person} with a {article of clothing}  on

can be understood as

The {person} with a {article of clothing}  on {the person}

So you can see that the preposition in would not work there:

The {person} with a {article of clothing}  in {the person}
The girl with a red dress in [her] ungrammatical
The girl with a red dress on [her] OK

To be in an article of clothing also means to be wearing it, but the person is inside the clothing.  With on, the clothing is on the outside of the person. It is simply a matter of how one conceptualizes clothing: are we in it or is it on us?

A: A and C are correct if the right answer is "which sentences mean the girl is wearing the dress."
Only D is really wrong.

The girl in the red dress

X in Y is used when Y surrounds X on a couple or more sides, or Y is a container of some sort.  This means the same as "The girl wearing the red dress."

The girl on the red dress

X on Y is used when Y is flat and X is above it and making contact with it.
 So this means the girl is sitting/standing on top of the dress, not wearing it.

The girl with the red dress on

On here is being used as an adverb to mean "physically in contact with and supported by a surface", which is also used to mean "that is being worn by her."

The girl with the red dress in

In can similarly be used as an adverb to mean "that is inside of X".   Unless the word "girl" means "something that is shaped like a girl but can be used to contain items" this sentence won't make any sense since you cannot put a dress inside of a girl.


text:
Q: How to embed a Youtube video in LaTeX Beamer How can I embed Youtube videos in presentations with Beamer? (Windows 7, editor: TeXstudio, TeXlive)
Here is what I tried so far (including internet search of cause): I already tried using vlc to download the video, which itself couldnt play the video afterwards.
I used a browser extension called video downloadhelper, but I am not really satisfied, because that doesn't use the source. Instead it makes a video of the screen.
I tried using the \movie{}{} command, but it doesn't want to work. TeXstudio (my editor) tells me:

You clicked on a video, but the video playing mode was disabled by you or the package creator.
Recompile TeXstudio with the option PHONON=true.

I didn't yet try to compile in cmd, but I will try that later today.
Thanks in advance.
edit:
I got the source for the youtube video via firefox with right click, inspect element, copy video url.
Still vlc cant read anything converted with vlc.


text:
Q: Can't get response code I want to get user AccessToken.
When the user clicks on Register/Login button :
            $.ajax({
            url: 'Register',
            type: 'GET',
            data: { m:true },
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                if (response.success) {
                } else {
                }
            },
            error: function () {
            }
            });

My register method :
            Uri uri = new Uri(FacebookHelpers.GetFacebookLoginURL());
            var res = await FacebookHelpers.FacebookRequest<object>(uri).ConfigureAwait(false);

In res, i want to get result from FacebookRequest to get code, than exchange that code for access token.
My GetFacebookLoginUrl function :
            var redirectUri = "https://www.facebook.com/connect/login_success.html";
            var uri = GetUri("https://www.facebook.com/dialog/oauth",
                Tuple.Create("client_id", FacebookAppId),
                Tuple.Create("redirect_uri", redirectUri),
                Tuple.Create("response_type", "code"),
                Tuple.Create("scope", "public_profile,email"),
                Tuple.Create("state", Convert.ToString(new Random().Next(9999)))
                );

In my FacebookRequest function :
        public static async Task<T> FacebookRequest<T>(Uri uri)
        {
            string json;
            using (HttpClient client = new HttpClient())
            {
                json = await client.GetStringAsync(uri).ConfigureAwait(false);
            }

            try
            {
                var result = JsonConvert.DeserializeObject<T>(json);
                return result;
            }
            catch (JsonException ex)
            {
                throw new ArgumentException("Unable to deserialize the Facebook response.", ex);
            }
        }

The issue appears when FacebookRequest function tries to get code from provided URL.

Unexpected character encountered while parsing value: <. Path '', line
  0, position 0.

Json response contains same page from where method has been called.
FacebookRequest does not returns code, it returns success instead.
Any idea ?
The goal : I want to get user from my database and link its account with my bot. Or if user does not exist, first register and than link with the bot.

A: You can not load the Facebook login dialog in the background - you have to redirect the user to that address. It has to be called in the user's browser; if you try and request it in the background, that won't work.
As for whether you get a code or an access token returned: You can specify that you want an access token returned directly - but in that case, the token is passed in the fragment part of your redirect URI, meaning you can only get it from there using client-side code. That is rather not an option here, I suppose. (If you need more info on that, the parameter response_type and possible values are described here, https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#logindialog)


text:
Q: Get street viewport/bounds On my website, I got a Google Maps autocomplete field which let's the user select an location (for example a city or a street).
Once the user has selected an address I automatically set the bounds of the map to the bounds of the location. For example if the location is a large city, the bounds will be zoomed out quite a bit, while they will be zoomed in if the user inputs a small street.
I want the entire location to be covered within the bound - so if it's a long street then the ENTIRE street should be within the map bounds.
Here is the code I use:
google.maps.event.addListener(autocomplete, 'place_changed', function () {
    var address = autocomplete.getPlace();
    if (address && address.geometry && address.geometry.location) {
        centerCoord = address.geometry.location;
        map.setCenter(new google.maps.LatLng(centerCoord.lat(), centerCoord.lng()));
        if (address.geometry.viewport) {
            map.fitBounds(address.geometry.viewport);
        } else {
            //this happens when inputting a street - no viewport or bounds are returned. How do I get the entire bounds of the street?
        }
    }
});

The issue is the fact that the API apparently doesn't return a viewport or bounds when inputting a street. How can I get the bounds in this case?
Setting the zoom level to a static value (eg. 16) doesn't work since the user could type in either a short street or a long street.
As requested, here's a JsFiddle that showcases my issue: https://jsfiddle.net/cy1o228e/5/.
Try entering a local street such as Rolighedsvej, Frederiksberg, Denmark and you will see that no bounds nor viewport is being returned.


text:
Q: Twilio Rest Api CallListRequest return null sometime I am using Twilio rest API for Twilio integration. Below is the sample code.
    string AccountSid ="1er23are1t23tete1";
    string AuthToken = "re5s3g5ds2v8f2v";
    var twilio = new TwilioRestClient(AccountSid, AuthToken);
    string trackingNumber ="";
    var request = new CallListRequest();
    request.From = FromPhone;
    request.StartTime = DateTime.Today;
    var calls = twilio.ListCalls(request);

Some time ListCalls method is returning null value and I am loosing full integration for this particular inbound call, please help me on this.

A: Twilio evangelist here.
I'd suggest checking the RestException property on your calls object to see if its null or not.  This will tell you if your request to the Twilio API is failing:
if (calls.RestException!=null)
{
    Debug.Writeline(calls.RestException.Message);
}

Hope that helps.


text:
Q: Showing $\lim_{n \to \infty}\int_0^1x^nf(x)\,d \mu =0$ Let $f:[0,1] \to [0, \infty]$ be a measurable function s.t. $\int_0^1 f \,d \mu < \infty$. I wanna show that $$\lim_{n \to \infty}\int_0^1x^nf(x)\,d \mu =0$$
I thought to use the dominated convergence theorem but I don't see how to start.
EDIT:
For the next step I should calculate $\int_0^1 \lim_{n \to \infty}x^nf(x) \,d \mu$. This should be zero but how, can I see this the best way? I was thinking about to show that $\lim_{n \to \infty}x^nf(x)=0$ for $x \in [0,1)$, but what is for $x=1$?

A: If you don't really want to use Lebesgue Dominated Convergence Theorem, you can simply use Monotone Convergence Theorem.
First of all, let us see the following basic fact: For $f_{N}\geq 0$ are such that $f_{N}(x)\downarrow 0$ for every $x$, and $\int f_{1}<\infty$, then $\int f_{N}\rightarrow 0$. This is a matter of Monotone Convergence Theorem if we look at the increasing sequence $(f_{1}-f_{N})_{N=1}^{\infty}$ and obtain that $\int f_{1}-f_{N}\rightarrow\int f_{1}$.
Now let $N$ be fixed. Then
\begin{align*}
\int_{0}^{1}x^{n}f(x)dx&=\int_{0}^{1-1/N}x^{n}f(x)dx+\int_{1-1/N}^{1}x^{n}f(x)dx\\
&\leq\left(1-\dfrac{1}{N}\right)^{n}\int_{0}^{1}f(x)dx+\int_{0}^{1}1_{[1-1/N,1]}(x)f(x)dx.
\end{align*}
Let $f_{N}(x)=1_{[1-1/N,1]}(x)f(x)$, then $f_{N}(x)\downarrow 0$, apply the basic fact just before, for $\epsilon>0$, let $N$ be such that
\begin{align*}
\int_{0}^{1}1_{[1-1/N,1]}(x)f(x)dx<\epsilon.
\end{align*}
Now $1-1/N<1$ and hence for large enough $n$, we have
\begin{align*}
\left(1-\dfrac{1}{N}\right)^{n}\int_{0}^{1}f(x)dx<\epsilon,
\end{align*}
for all such $n$,
\begin{align*}
\int_{0}^{1}x^{n}f(x)dx<2\epsilon.
\end{align*}

A: Hint:
You have the exact right idea with the dominated convergence theorem!
On $[0,1]$ we see $x^n f \to 0$ pointwise almost everywhere
(do you see why? What about if $f = \infty$ at certain points?).
Then, as mentioned in the comments, $|x^n f| \leq |f|$. Can you use this, plus the dominated convergence theorem, to prove that $\int x^n f \to \int 0 = 0$?

I hope this helps ^_^


text:
Q: Remove accidental comment upvote Since cancelling upvotes on comments was implemented on the website, I think it should be default on the mobile application too.
I used the mobile app for the first time ever to reply to a comment, and accidentally hit the wrong button.
Now someone I totally disagree with got my upvote (not the end of the world, but would be nice to unvote) and I cannot remove it. I even tried visiting the same site literally 20 seconds later through my PC's web browser, but I was unable to unvote it even there, the button is not pressable.


text:
Q: Exporting wiki to a word document - WSS Is there a way to export a wiki page to a MS word document in WSS? Ideally, I would like to add a link on every WIKI page when clicked would export the content to a Word document. Any free plugins to do this?
Any help is appreciated

A: Answer Copied Entirely from here (even though it is actually a totally different question)

There is no such tool provided by Microsoft at this time.
There is one being developed though in the SharePoint Community Kit.
Wiki Import/Export Tool
The EWE team is at a very early stage of designing an import/export tool for the SharePoint wiki. The goal is for this tool to be able to import from other wiki products such as FlexWiki, MediaWiki, and TWiki, and Confluence and also from Word and OneNote as well as to export to Word via HTML (per page) and MHTML (entire wiki) formats.
For this CKS 2.0 pre-release, the EWE team is making available a fairly stable build of the FlexWiki Import Tool, for which the source code was graciously donated by Michael Cheng, a developer in the SharePoint product group. This is a one-off tool that will ultimately be converted to a plug-in for the Wiki Import/Export Tool, so if you're currently using FlexWiki, please test the tool and provide feedback.


text:
Q: FB scope publish_actions not asking in our apps we have the option to share activity on Facebook after which the users get a small reward. In recent days this feature has stopped working for some of our users because we didn't get "post_id" from your side which we need to determine if the user should get a reward.
We found out that this happens when the user hasn't given us the "publish_actions" right. Therefore we have added a check for this right and we try to request it this way:
FB.api('/me/permissions/publish_actions', function(response) {
  // pokud mame pravo na zverejneni obsahu hned postujeme
  if (response.data && response.data[0] && response.data[0]['status'] === 'granted') {
    postShareReport();
  } else {
    // pokud nemame, tak si zkusime vyzadat pravo
    FB.login(function(response) {
       if (response.authResponse) {
         // pokud nam ho dal, tak postujeme
         if(response.authResponse.grantedScopes && response.authResponse.grantedScopes.indexOf('publish_actions') !== -1) {
            postShareReport();
         }
       }
     }, {scope: "email,publish_actions",return_scopes: true, auth_type: 'rerequest'});
  }
});

However, here we encountered another problem. The publish_actions right is not requested from some users even though they haven't given us this right. The login process does go through, however. The user doesn't receive the window with the option to give us this right.
Thank you
Kind regards

A: Most permissions need to get reviewed by Facebook: https://developers.facebook.com/docs/facebook-login/review
Without review, publish_actions only works for users with a role in the App. Ohter users don´t get asked for the permission in the authorization process.
Btw, not getting a Post ID or information if the user really shared something is intentional, because rewarding the user in any way for sharing is not allowed. You need to read the platform policy before creating any App, that rule is in there since years:

Only incentivize a person to log into your app, enter a promotion on
  your app's Page, or check-in at a place. Don't incentivize other
  actions.

Source: https://developers.facebook.com/policy/


text:
Q: authentication issue with rest api - rest_cannot_create I am using the rest api in Wordpress. For authentication I use the Basic authentication plugin (JSON Basic Authentication)
I use this request (from both postman and nodejs):
POST /wp-json/wp/v2/posts HTTP/1.1
Host: **************
Authorization: Basic *********************
Content-Type: application/json
Cache-Control: no-cache

{ "title": "test", "content": "test", "status": "private", "excerpt": "test" }

When testing locally on my server, it works fine but on a VPS I get the following error:
{
    "code": "rest_cannot_create",
    "message": "Sorry, you are not allowed to create posts as this user",
    "data": {
        "status": 401
    }
}

I know the user credentials are correct and the user is allowed to create posts.
I suspect that the auth header is lost somewhere before arriving to rest-api. But where should I start debugging? Which logs?

A: Authorization header is usually stripped by Apache.
You can fix it with .htaccess
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

A: If you are here because you have already tried everything and still can't create resources via Wordpress Rest API, then let me share what worked for me.
First of all, let me give you some context here, I got WordPress launched on an AWS instance using Bitnami.
Then I installed WooCommerce and enabled its API in order to play with it as a sandbox system. Immediately after that, I tried to create products using Postman but every time I got errors like "woocommerce_rest_cannot_create" ("Sorry, you are not allowed to create resources."). I tried different authentication methods such as OAuth and Basic Auth but none of them worked.
So I thought that maybe I should try WordPress API endpoint instead (instead of Woocommerce's endpoint) and see if I could create posts or users, though that didn't work either. I got errors like:

*

*"rest_cannot_create" ("Sorry, you are not allowed to create posts as this user.")

*"rest_cannot_create_user" ("Sorry, you are not allowed to create new users")

Here is what worked for me:

*

*Install Basic Auth plugin, you can install it by cloning the repo into /opt/bitnami/apps/wordpress/htdocs/wp-content/plugins and then activate it from the plugins page in WP Admin page. Or you can also download the repo as a zip and install from a file from the plugins page in WP Admin.

*Change postman (or whatever you are using to send your requests) to use Basic Auth. Use the creds of an existing Administrator user.

*Edit the .htaccess file available in /opt/bitnami/apps/wordpress/htdocs (This file is hidden, don't freak out if you can't see it)

*Add a new line under RewriteEngine On and insert RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}] save and exit

*Edit /opt/bitnami/apps/wordpress/conf/httpd-app.conf add a new line after RewriteEngine On

*In the new line insert: RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] save and exit

*Restart Apache: sudo /opt/bitnami/ctlscript.sh restart apache

*(OPTIONAL) Install Application Passwords By George Stephanis
Then I tried again from Postman and everything worked flawlessly.
For more details check:
https://community.bitnami.com/t/setting-up-api-access-to-wordpress-on-aws-ec2-instance/60589/7


text:
Q: Why do I get a compiling error that says error: 'else' without a previous 'if'? When I try to compile the code I get an error that says else without a previous if:
// Fibonacci series using recursion
#include <iostream>
using namespace std;
int fib (int n);

int main()
{
     int n, answer;

     cout << "\n\n\t\tEnter number to find: ";
     cin >> n;
     cout << "\n\n";

     answer = fib(n);

     if(n < 3 && n > 1)
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";
     {
         if(n < 3)
             cout << answer << " is the " << n;
             cout << "st Fibonacci number\n";
         else
             cout << answer << " is the " << n;
             cout << "rd Fibonacci number\n";
     }
     else
         cout << answer << " is the " << n;
         cout << "th Fibonacci number\n";

     return 0;
}

int fib (int n)
{
     cout << "Processing fib (" << n << ")... ";

     if (n < 3)
     {
         cout << "Return 1!\n";
         return 1;
     }
     else
     {
         cout << "Call fib(" << n-2 << ") ";
         cout << "and fib(" << n-1 << ").\n";
         return(fib(n-2) + fib(n-1));
     }
}

A: Surely it's a problem about the key brackets:
int main()
{
     int n, answer;

     cout << "\n\n\t\tEnter number to find: ";
     cin >> n;
     cout << "\n\n";

     answer = fib(n);

     if(n < 3 && n > 1) {
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";

         if(n < 3) {
             cout << answer << " is the " << n;
             cout << "st Fibonacci number\n";
         } else {
             cout << answer << " is the " << n;
             cout << "rd Fibonacci number\n";
         }
     }
     else {
         cout << answer << " is the " << n;
         cout << "th Fibonacci number\n";
     }
     return 0;
}

A: You're missing accolades (curly brackets) after your if:
if(n < 3 && n > 1)
    cout << answer << " is the " << n;
    cout << "nd Fibonacci number\n";
{
    if(n < 3)

means
 if(n < 3 && n > 1)
 {
     cout << answer << " is the " << n;
 } // end of if
 cout << "nd Fibonacci number\n"; // always executed
 { // new anonymous block
     if(n < 3)

A: Because you didn't properly use braces ("curly brackets", { and }) in your main.
First let's take this inner part of the code:
      if(n < 3)
         cout << answer << " is the " << n;
         cout << "st Fibonacci number\n";
      else
         cout << answer << " is the " << n;
         cout << "rd Fibonacci number\n";

That current indentation is "wrong" and misleading. If you copy-paste it into a code editor and use auto-formatting (auto-indent will suffice), you'll get:
      if(n < 3)
         cout << answer << " is the " << n;
      cout << "st Fibonacci number\n";
      else
         cout << answer << " is the " << n;
      cout << "rd Fibonacci number\n";

which shows you the real "meaning" of the code. After adding braces and blank lines for clarity:
      if(n < 3)
      {
         cout << answer << " is the " << n;
      }

      cout << "st Fibonacci number\n";

      else
      {
         cout << answer << " is the " << n;
      }

      cout << "rd Fibonacci number\n";

As you can see, only the first cout statement is conditioned by the if. The second one will always be executed. Then comes an else that follows a "plain", "unconditional" statement, not a "conditioned" statement/block (a block of statement(s) as a whole is a statement too).
To fix this part you must wrap all the conditioned statements in braces:
      if(n < 3)
      {
         cout << answer << " is the " << n;
         cout << "st Fibonacci number\n";
      }
      else
      {
         cout << answer << " is the " << n;
         cout << "rd Fibonacci number\n";
      }

or in a more compact style:
      if(n < 3) {
         cout << answer << " is the " << n;
         cout << "st Fibonacci number\n";
      } else {
         cout << answer << " is the " << n;
         cout << "rd Fibonacci number\n";
      }

such that the full block-statement is conditioned.
Now that the "inner" if-else part is fixed, let's take the "outer" if-else:
     if(n < 3 && n > 1)
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";
     {
      /* ... fixed inner if-else ... */
     }
     else
     cout << answer << " is the " << n;
     cout << "th Fibonacci number\n";

Let's use a code formatter again:
     if(n < 3 && n > 1)
         cout << answer << " is the " << n;
     cout << "nd Fibonacci number\n";
     {
         /* ... fixed inner if-else ... */
     }
     else
         cout << answer << " is the " << n;
     cout << "th Fibonacci number\n";

The real meaning should now be clear (using compact style here):
     if(n < 3 && n > 1) {
         cout << answer << " is the " << n;
     }

     cout << "nd Fibonacci number\n";

     {
         /* ... fixed inner if-else ... */
     }

     else {
         cout << answer << " is the " << n;
     }

     cout << "th Fibonacci number\n";

The funny block alone in the middle (code inside braces but not directly following an if/else) is actually an anonymous block, which just introduces an inner scope (variables defined inside will not exist anymore after the closing }). It can be see as a plain statement (unconditional), just like the cout << "nd Fibonacci number\n"; just above it.
Once again, the fix is obvious:
     if(n < 3 && n > 1) {
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";

         /* ... fixed inner if-else ... */

     } else {
         cout << answer << " is the " << n;
         cout << "th Fibonacci number\n";
     }

A: Try this:
int main()
{
     int n, answer;

     cout << "\n\n\t\tEnter number to find: ";
     cin >> n;
     cout << "\n\n";

     answer = fib(n);

     if(n < 3 && n > 1)
     {
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";

         if(n < 3)
         {
             cout << answer << " is the " << n;
             cout << "st Fibonacci number\n";
         }
         else
         {
             cout << answer << " is the " << n;
             cout << "rd Fibonacci number\n";
         }
     }
     else
     {
         cout << answer << " is the " << n;
         cout << "th Fibonacci number\n";
     }
     return 0;
}

Make sure that your ifs and elsees are accordingly within the curly brackets.

A: You did not add brackets in some if else clause with multiple statement. Don't do this in real world coding.
Change the code as follows:
// Fibonacci series using recursion
#include <iostream>
using namespace std;
int fib (int n);

int main()
{
     int n, answer;

     cout << "\n\n\t\tEnter number to find: ";
     cin >> n;
     cout << "\n\n";

     answer = fib(n);

     if(n < 3 && n > 1)
      {
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";

      if(n < 3)
     {
         cout << answer << " is the " << n;
         cout << "st Fibonacci number\n";
     }
      else
      {
         cout << answer << " is the " << n;
         cout << "rd Fibonacci number\n";
       }
     }
     else {
     cout << answer << " is the " << n;
     cout << "th Fibonacci number\n";
     }
     return 0;
}

int fib (int n)
{
     cout << "Processing fib (" << n << ")... ";

     if (n < 3)
     {
         cout << "Return 1!\n";
         return 1;
     }
     else
     {
         cout << "Call fib(" << n-2 << ") ";
         cout << "and fib(" << n-1 << ").\n";
         return( fib(n-2) + fib(n-1));
     }
}

A: You forgot to use {} on internal if's. It should be
if(n < 3)
{
   cout << answer << " is the " << n;
   cout << "st Fibonacci number\n";
}
else
{
    cout << answer << " is the " << n;
    cout << "rd Fibonacci number\n";
}

A: I believe you are missing curly brackets after the if(n < 3), so the conditional only applies to the line below.  Then the compiler hits the 'else'......

A: All your answers about the curly brackets were correct, but the code I needed was like this:
if (n > 3)
{
    cout << answer << " is the " << n;
    cout << "th Fibonacci number\n"; // E.g., "5th Fibonacci number"
}
else
{
    if(n == 3)
    {
        cout << answer << " is the " << n;
        cout << "rd Fibonacci number\n";  // "3rd Fibonacci number"
    }
    else
    {
       if(n < 3 && n > 1)
       {
           cout << answer << " is the " << n;
           cout << "nd Fibonacci number\n"; // "2nd Fibonacci number"
       }
       else
       {
           cout << answer << " is the " << n;
           cout << "st Fibonacci number\n"; // "1st Fibonacci number"
       }

    }
}


text:
Q: Event Data_Column_Changed is lost when a subset DataTable is derived from another DataTable I used this SO answer to get a subset (DataTable2 for example) from an original Data Table(DataTable1-  for example).
It worked and I got the desired DataTable2, until I realized that the events that were assigned to the original DataTable1 do not exist for the subset (DataTable2).
How can I preserve the events associated with the first DataTable1?  The events in question are
(Data_Column_Changed and DataRowChanged)


text:
Q: reading gmail is failing with IMAP I am running a cron job which executes the python script for reading gmail (2 min interval). I have used imaplib for reading the new mails. This was working fine until yesterday. Suddenly its throwing below error

imaplib.error: [AUTHENTICATIONFAILED] Invalid credentials (Failure)

and sometimes i am getting the below error

raise self.abort(bye[-1]) imaplib.abort: [UNAVAILABLE] Temporary System Error

When i run the same script on a different machine. Its working fine. I am assuming that the host has been blacklisted or something like that.
What are my options ?
I cant generate the Credentials (Gmail API) as this is under company domain account.

A: try with:
1)
https://myaccount.google.com/lesssecureapps?pli=1
2) Gmail Settings -> Forwarding and POP / IMAP -> IMAP Acess to Enable IMAP

A: Ensure you have entered the right password

Even after that if it is not working

*

*Enable the IMAP Access at: Gmail Settings> Forwarding and POP / IMAP> IMAP Acess

*Enable 2-factor authentication for the google account

*then generate an app-specific password    (https://myaccount.google.com/apppasswords)

*Use this newly generated password for imap login

A: Some apps and devices use less secure sign-in technology. So we need to enable Less secure app access option from gmail account.
Steps:

*

*Login into Gmail

*Go to Google Account

*Navigate to Security section

*Turn on access for Less secure app access
By following above steps, issue will be resolved.

A: Got the same error and it was fixed by getting the new google app password. Maybe this will work for someone

A: This can be solved in two steps:

*

*Turn on the Less secure app access at: Google Account> Security> Less secure app access

*Enable the  IMAP Access at: Gmail Settings> Forwarding and POP / IMAP> IMAP Acess

A: Thanks guys. Its working now. The issue was that the google blocked our network.. because of multiple attempts. I tried that unlock URL from a different URL and it didnt work. The catch is that, we have to run that URL in the machine where you are trying to run the script. Hope it may help someone :)

A: Google Gmail - Security - Less secure app access ... won't work anymore !
See  https://support.google.com/accounts/answer/6010255?hl=en
"To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password."
Regards
Diego


text:
Q: From this stemmed my misinterpretation From this stemmed my misinterpretation of the meaning.
Is this sentence grammatically OK in terms of the word order? Is here inversion possible as in the case of an adverbial expression of place at the beginning on the sentence (On the table was all the money we had lost)?

A: Yes, your word order here is fine. While the from here is not strictly physical, it relies on a physical metaphor, so expression-of-place inversion is perfectly appropriate. (There are no actual physical stems here, either, but we talk about your misunderstanding as it if had a stem, which comes from somewhere.)
This inversion sounds slightly more poetic, but it is perfectly correct and understandable:

The gates of Atlantis stood before me. (ordinary)
Before me stood the gates of Atlantis. (poetic)

One side note: "Is here inversion possible" should be "Is inversion possible here" (or possibly, "Is inversion here possible"). Generally, here should come after the adjective or verb it modifies.


text:
Q: How to wrap multi actionCreators into one props? I'm getting the following error:
Uncaught TypeError: this.props.dispatch is not a function
Here's my component:
import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      userPositionActions: bindActionCreators(userPositionActions, dispatch),
      jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);

What am I doing wrong here?

A: Per my comment, this would be the correct syntax to bind multiple sub-objects worth of action creators:
function mapDispatchToProps(dispatch) {
    return {
        userPositionActions : bindActionCreators(userPositionActions, dispatch),
        jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
}

A: Since you have already used mapDispatchToProps, dispatch wont be available to the component as a prop. Since you have used mapDisptachToProps, the jobs actions will be available as props and you can use them like
componentDidMount() {
    this.props.actions.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

However you can simplify it further like
function mapDispatchToProps(dispatch) {
  return bindActionCreators({userPositionActions, jobTitleSkillsActions}, dispatch)
}

...

componentDidMount() {
    this.props.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

A: As you have provided mapDispatchToProps to connect function, dispatch is not passed as prop to your component.
Your componentDidMount code should be like this:
componentDidMount() {
  const actions = this.props.actions
  actions.userPositionActions.loadUserPositions()
  var job_title_id = this.props.user_positions[0].job_title_id;
  actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id)
}


text:
Q: how can I move a string date to a new component with 3 fields I have a component called DateComponent, and it contains 3 inputs (year/month/day). I also have a component which contains a formGroup and has a formControlname date which is like yyyy-mm-dd.
If I want to go through the FormGroup path, how can I get the data from DateComponent nicely as yyyy-mm-dd to the form in parent component?
I tried to use ControlValueAccessor, but the problem is I have 3 ngmodel (day, month, year) in DateComponent while in parent there is one which is Date.
I really prefer not to break down my formControl from date to 3 fields. Any thoughts or solution.

A: When we make a custom form control extending ControlValueAccessor the important part is when we define registerOnChange and when "something" change we call to the function.
A simple .html
<input [ngModel]="year" (ngModelChange)="year=+$event;change()">
<input [ngModel]="month" (ngModelChange)="month=+$event;change()">
<input [ngModel]="day" (ngModelChange)="day=+$event;change()">

See that each change in an input call to the function "change()"
The important part:
  year:number;
  month:number;
  day:number;
  constructor() { }

  onChange:any; //<--define a function OnChange

  //here we give value to our function "onChange"
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  //each change of the inputs
  change(){
    if (this.year && this.month && this.day)
    {
      const date=new Date(this.year,this.month-1,this.day)
      this.onChange(date); //<--we call to the function onChange
                           //we pass as argument the value we want to get our
                           //control
    }

   //the writeValue is executed onTime at first with the value
   //of the control
   writeValue(value: any[]|any): void {
    this.year=value?value.getFullYear():null;
    this.month=value?value.getMonth()+1:null;
    this.day=value?value.getDate():null;
  }

Update to not fight with GTM replace the functions as
writeValue(value: any[] | any): void {
    if (value) {
      const date=new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
      this.year = value.getFullYear();
      this.month = value.getMonth() + 1;
      this.day = value.getDate();
      this.change()
    }
  }

  change() {
    if (this.year && this.month && this.day) {
      const date = new Date(Date.UTC(this.year, this.month - 1, this.day));
      this.onChange(date);
    }
  }

See stackblitz

A: you can maybe do something like this
let date = 10
let month = 1
let year = 2019

let finalDate = new Date()
finalDate = new Date(finalDate.setDate(date))
finalDate = new Date(finalDate.setMonth(month))
finalDate = new Date(finalDate.setFullYear(year))
console.log(finalDate)

the final output would be something like this
2019-02-10T04:47:37.886Z

if you want to remove the time you can do that using datepipe
console.log(this.datePipe.transform(finalDate, 'yyyy-MM-dd'))

the output of above console.log would you be
2019-02-10


text:
Q: Revert changes done if application amidst operations I am performing a series of steps, when I run the console application. Let's say the number of steps are 8, and it fails somewhere at the 4th step.
I wanted to be able to revert the first steps that I did before it failed. How can this be done, if it fails at any of steps?

A: If you implement the steps using the command pattern where each step knows how to do itself as well as undo itself.  Then you would be able to just loop through the steps that have been done and undo them.
You may also be interested in this question Implementing the command pattern.