text:
Q: Does DOMContentLoaded closing tag always have to be at the end of doc? Is there a way to get JavaScript code to work without having to encompass my code in a closing tag of DOMContentLoaded. The first example below does not work because the closing tag for DOMContentLoaded is before the code.
I'm worried I'm going about this the wrong way because once my code grows to a few hundred lines intuitively it feels wrong to have all of it inside this function? Is there a more efficient way in which I do not have to keep all of my code in such a function but still allow the page to load before proceeding to the enclosed code which as I understand it is the purpose of the DOMContentLoaded?
I have attempted numerous types of JavaScript queries and event listeners but still it does not work unless everything is enclosed in the DOMContentLoaded.
// **Example 1 - this code works after DOMContentLoaded**
document.addEventListener('DOMContentLoaded', function() {
})

// **the below code does not run**
document.querySelector("button").onclick = count;

let counter = 0;

function count() {

counter++;
document.querySelector("#counter").innerHTML = counter;
}

// example 2 - this code work
document.addEventListener('DOMContentLoaded', function() {

document.querySelector("button").onclick = count;

let counter = 0;

function count() {

  counter++;
  document.querySelector("#counter").innerHTML = counter;
}
// **If my code was large I feel that this cannot be a very efficient**
// **way to have put it all within the DOMContentLoaded closing tag**

})   // **DOMContentLoaded closing tag**

A: I now come to understand that the part of the code that needs to be within the DOMContentLoaded function are the calls to other functions which rely on an initial action to be taken from the web page which requires it to be fully loaded.
I also understand that other JavaScript can be run and shown to the user without the function or function call being within the Dom function. Such as alert() because it doesn't rely on elements from the HTML page being loaded beforehand.
Thank you for your help Jenkins and Hamms.


text:
Q: Initialize other provider after APP_INITIALIZE I have a little bootstrapping problem using Angular 4.
I have a config file (json) that I'm loading from the server as my application starts (see also here). This works so far.
Now I have a dependency that requires config values to be passed in a forRoot method. The implementation looks like this:
static forRoot(config: AppInsightsConfig): ModuleWithProviders {
    return {
        ngModule: ApplicationInsightsModule,
        providers: [
            { provide: AppInsightsConfig, useValue: config }
        ]
    };
}

My Idea was to import the module without forRoot(), but providing the AppInsightsConfig by after the configs (from server) have been loaded.
@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: [...sharedConfig.declarations],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ApplicationInsightsModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin },
        { provide:
            APP_INITIALIZER,
            useFactory: (configService: ConfigService) => () => configService.load(),
            deps: [ConfigService], multi: true
        },
        { provide:
            AppInsightsConfig,
            useFactory: (configService: ConfigService) => {
                // outputs undefined, expected it to have the config
                console.log(configService.config);
                return { instrumentationKey: 'key from config' }
            },
            // My idea was, if I add APP_INITIALIZER as dependency,
            // the config would have been loaded, but this isn't the case.
            deps: [APP_INITIALIZER, ConfigService]
        },
        AppInsightsService
    ]
})

How can I provide AppInsightsConfig or another service AFTER my configs have been loaded?

A: Finally, I came up with following solution:

*

*I merged the sources of the angular-application-insights package (was not my original intention) to my code base to be able to alter things that made it hard for me to do the bootstrapping how I wanted to. I also fighted against cyclic dependencies. Thanks to MarkPieszak for sharing your library.

This is how my app-module looks like now:
import { Resolve, Router } from '@angular/router';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { sharedConfig } from './app.module.shared';

import { SiteControlModule } from './site-control/site-control.module';
import { SiteControlComponent } from './site-control/site-control.component';
import { AuthModule } from './auth/auth.module';

import { ConfigService } from './core/config/config.service';

import { ApplicationInsightsModule } from './application-insights/application-insights.module';
import { ApplicationInsightsService } from './application-insights/application-insights.service';

import { CoreModule } from './core/core.module';

let initializeConfig = (aiService: ApplicationInsightsService, configService: ConfigService) => () => {
    let loadConfigPromise = configService.load();

    loadConfigPromise.then(() => {
        aiService.config = configService.config.applicationInsights;
        aiService.init();
    });

    return loadConfigPromise;
};

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: [...sharedConfig.declarations],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AuthModule,
        ...sharedConfig.imports,
        CoreModule.forRoot(),
        ApplicationInsightsModule.forRoot(),
        SiteControlModule
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin },
        { provide:
            APP_INITIALIZER,
            useFactory: initializeConfig,
            deps: [ ApplicationInsightsService, ConfigService ],
            multi: true
        }
    ]
})
export class AppModule {
}

config.service.ts
import { Injectable } from '@angular/core';
import { Headers, RequestOptions,  Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

import { Config } from './models/config.model';

@Injectable()
export class ConfigService {

    config : Config;

    constructor(private http: Http) {
        console.log('constructing config service');
    }

    public load(): Promise<void> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let url = 'environment.json';

        let promise = this.http.get(url, { headers })
            .toPromise()
            .then(configs => {
                console.log('environment loaded');
                this.config = configs.json() as Config;
            })
            .catch(err => {
                console.log(err);
            });

        return promise;
    }

}

Altered part of the application-insights.service.ts
import { Injectable, Optional, Injector } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { AppInsights } from 'applicationinsights-js';
import 'rxjs/add/operator/filter';
import IAppInsights = Microsoft.ApplicationInsights.IAppInsights;

import { ApplicationInsightsConfig } from '../core/config/models/application-insights.model';

@Injectable()
export class ApplicationInsightsService implements IAppInsights {

    context: Microsoft.ApplicationInsights.ITelemetryContext;
    queue: Array<() => void>;
    config: Microsoft.ApplicationInsights.IConfig;

    constructor(@Optional() _config: ApplicationInsightsConfig, private injector: Injector) {
        this.config = _config;
    }

    private get router(): Router {
        return this.injector.get(Router);
    }

    ...

application-insights.module.ts
import { NgModule, ModuleWithProviders, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ApplicationInsightsService} from './application-insights.service';

export * from './application-insights.service';

@NgModule({
    imports: [ CommonModule ],
    declarations: [],
    exports: [],
    providers: []
})

export class ApplicationInsightsModule {

    constructor(@Optional() @SkipSelf() parentModule: ApplicationInsightsModule) {
        if (parentModule) {
            throw new Error(
                'ApplicationInsightsModule is already loaded. Import it in the AppModule only');
        }
    }

    static forRoot(): ModuleWithProviders {
        return {
            ngModule: ApplicationInsightsModule,
            providers: [ ApplicationInsightsService ]
        };
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if every word in a cell is in another column - Google Sheets Trying to see if every word in a given cell is in a list in another column. For example:
https://i.stack.imgur.com/SGdsU.png
Thanks in advance!

A: try:
=ARRAYFORMULA(COLUMNS(SPLIT(A9:A10, ", "))=
 LEN(SUBSTITUTE(FLATTEN(QUERY(TRANSPOSE(
 IFERROR(1/(1/REGEXMATCH(SPLIT(A9:A10, ", "),
 TEXTJOIN("|", 1, A2:A5, "^$"))))),,9^9)), " ", )))


text:
Q: Vue js: function remove not working properly in my code i have code below in Vue js that shows Categories from API and whenever i click on any of them it add it to the array AddCategory and post it to API, also i've implemented button Removeall that whenever i click on it, it remove all the selected categories in array (it will empty the array) and it works fine. my problem is when i want to click again on the selected single category (in function remove below) it's not poping it up from array however it pushed it twice, any help?

<template>
  <b-row class="categories-row">
            <div
              class="categories"
              v-for="(category, index) in categories"
              :key="index"
              @click="Add(category._id, index)"
              :class="[selectedIndex.includes(index) ? 'green' : 'gray']"
              required
            >
              {{ category.category_name }}
            </div>
          </b-row>

</template>

export default {

  data() {
    return {
      categories: [],
      selectedIndex: [],
      AddCategory: [],

      posts: {
        description: null,
        questionTitle: null,
        categories: null,

      },
    };
  },
  methods: {
    Add(AddCategory, index) {

  if (this.selectedIndex.includes(index))
        this.Remove(index);
      else
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);
    },
      Remove(index) { //not working
      this.selectedIndex.splice(this.selectedIndex.indexOf(index),1);
    },

    RemoveAll() {
      this.AddCategory = [];
      this.selectedIndex.splice(this.AddCategory);
    },}}

A: try this:
Remove(index) {
      this.selectedIndex = this.selectedIndex.filter((item)=> item !== index) ;
}

Edited:
@sara97 maybe you need remove it from this.AddCategory too.
Edited:
@sara97 and because it runs "this.AddCategory.push(AddCategory);" everytime. use {} in if and else.
  Add(AddCategory, index) {
   if (this.selectedIndex.includes(index)) {
        this.Remove(AddCategory,index);
      }else{
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);}
    },

  Remove(AddCategory,index) {
      this.selectedIndex = this.selectedIndex.filter((item)=> item !== index);
      this.AddCategory = this.AddCategory.filter((item)=> item !== AddCategory)
    },


text:
Q: Double representation differences We have two projects running on .NET Core 3.1.420. One project is a copy of the other, with some changes to its UI/backend logic.
Both projects have the following class, with the exact same values.
public class DebuggerOptions
{
    public double Double1 => 0.08;
    public double Double2 => 0.015;
    public double Double3 => 0.05;
}

When we inspect the DebuggerOptions instance in the "old" project. We're seeing the correct representation of the doubles.
In the "new" project we're seeing values like

*

*Double1 = 0.080000000000000002

*Double2 = 0.014999999999999999

*Double3 = 0.050000000000000003

I'm personnaly seeing these differences on two machines running Windows 11. My colleague tried running both projects on his machine running Windows 10 and he is seeing the correct (exact) representation.
We're doing some precise calculations and these doubles are inputs which cause the result to be way off.
Has something changed to the IEEE 754 implementation in Windows 11? Are we missing some configuration? We're kind of lost at this point. Thank you in advance.

A:
I'm personally seeing these differences on two machines running Windows 11. My colleague tried running both projects on his machine running Windows 10 and he is seeing the correct (exact) representation.

You have not posted how you are personally seeing these differences.  Instead, post code that reports the values.
Your colleague's approach is also not posted.  Colleague's approach is not seeing the exact values.
double can store about 264 different values*1 exactly.  0.08, 0.015, 0.05 are not in that set - instead nearby values are used.  The different values you are seeing are due to the different ways of examining that data.  Instead, report values with code in floating point hexadecimal notation, or print exponentially with at least 17 significant decimal digits.

*1 All such values are some integer times a power-of-two.
See Dyadic rational.


text:
Q: nested loops and increment user input I'm trying to print user input numbers and indent them by that number of spaces. I can't seem to get the numbers to indent, however, I am able to print them all vertically. Any help? Here is my code.
 for (i = 0; i <= userNum; i++) {
      for (j = 0; j < i; j++) {
          System.out.println(i);
          break;

If a user entered the number 3, my output would currently look like this:
1
2
3

When it should look like this:
   1
    2
     3

A: This should do it
 for (int i = 0; i <= userNum; i++) {
      for (int j = 0; j < i; j++) {
          System.out.print(" ");
      }
      System.out.println(i);
 }

A: You can try to add another for loop within that for loop. The print statement would be after this nested for loop. The inner loop would start from zero to i+1. In this for loop, you can print the spaces or tabs. Then after the for loop you can print the number. Make sure you do not include a new line inside the print statement in the inner for loop.

A: You haven't added the code yet to add the indenting. Try this:
public static void printNum(int userNum) {
    for (int i = 0; i < userNum; i++) {
        System.out.print(" ");
    }
    System.out.print(userNum+ "\n");
}

Calling it with:
printNum(10);
printNum(1);
printNum(2);
printNum(3);

Gives the following:
run:
          10
 1
  2
   3
BUILD SUCCESSFUL (total time: 0 seconds)

A: public class Program {

    public static void main(String[] args) {
        int i = 3; // or your userNum
        // this loop will iterates through 1 to i (or 1 to userNum for you)
        for (int j = 1; j <= i; j++) {
            // this loop iterates until j2 equals j (e.g. if j = 5, this loop will iterates 4 times)
            for (int j2 = 1; j2 < j; j2++) {
                // prints the space(s)
                System.out.print(" ");
            }
            // prints the current number (in the first loop) and line break
            System.out.println(j);
        }
    }
}

A: I hope this solves your problem :
for (i = 1; i <= userNum; i++)
      System.out.format("%+(i-1)+s]%n", i);


text:
Q: Unsupported major.minor version 52.0 in elasticsearch 5.5.3 C:\Program Files\Elastic\Elasticsearch\bin>.\elasticsearch.exe
java.lang.UnsupportedClassVersionError: org/elasticsearch/bootstrap/Elasticsearch : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

Exception in thread "main"

A: OP faced this issue as he was using multiple JDK, and one which was used wasn't compatible with ES.
Read more about this error here How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
Once, he used the correct JDK, which was compatible with elasticsearch, he was able to resolve the error.


text:
Q: Applying multiple colors to the single cell in EPPlus? I am using EPPlus to generate report file. There is a column which does not intended to be used for any filtering/sorting logic but contains line-by-line data about the subject of the row.
Customer wants it to be filled by different colors as shown in the attached picture.

I've already found similar questions and correct answers here and here, but these answes works only for the case when the whole cell need to be filled by the single color.
I wonder if there a way to implement my case programmatically with EPPlus or the only way to achive such feature is to modify the cell's metadata manually via OpenXML library or even by modifying underlying XML-file?

A: Create a Console app named MultipleColorsInACell and copy and paste this below code.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Data;
using System.IO;

namespace MultipleColorsInACell
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                WorkbookPart workbookPart = null;

                try
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
                        {
                            workbookPart = excel.AddWorkbookPart();
                            workbookPart.Workbook = new Workbook();
                            uint sheetId = 1;
                            excel.WorkbookPart.Workbook.Sheets = new Sheets();
                            Sheets sheets = excel.WorkbookPart.Workbook.GetFirstChild<Sheets>();

                            string relationshipId = "rId1";
                            WorksheetPart wSheetPart = workbookPart.AddNewPart<WorksheetPart>(relationshipId);
                            string sheetName = "MultipleColorsInACell";
                            Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
                            sheets.Append(sheet);

                            Worksheet worksheet = new Worksheet();

                            wSheetPart.Worksheet = worksheet;

                            SheetData sheetData = new SheetData();
                            worksheet.Append(sheetData);

                            string[] excelColumns = new string[] { "A", "B", "C", "D", "E", "F", "G" };

                            Row row1 = new Row() { RowIndex = (UInt32Value)5U, Spans = new ListValue<StringValue>() { InnerText = "9:9" }, DyDescent = 0.3D };

                            Cell cell1 = new Cell() { CellReference = "I5", DataType = CellValues.SharedString };
                            CellValue cellValue1 = new CellValue();
                            cellValue1.Text = "0";

                            cell1.Append(cellValue1);

                            row1.Append(cell1);

                            sheetData.Append(row1);

                            SharedStringTablePart sharedStringTablePart1 = workbookPart.AddNewPart<SharedStringTablePart>("rId4");
                            GenerateSharedStringTablePart1Content(sharedStringTablePart1);

                            excel.Close();
                        }

                        FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "MultipleColorsInACell.xlsx", FileMode.Create, FileAccess.Write);
                        memoryStream.WriteTo(fileStream);
                        fileStream.Close();
                        memoryStream.Close();
                    }
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
            catch (Exception ex)
            {

                // logging, etc.
            }
        }

        // Generates content of sharedStringTablePart1.
        private static void GenerateSharedStringTablePart1Content(SharedStringTablePart sharedStringTablePart1)
        {
            SharedStringTable sharedStringTable1 = new SharedStringTable() { Count = (UInt32Value)1U, UniqueCount = (UInt32Value)1U };

            SharedStringItem sharedStringItem1 = new SharedStringItem();

            Run run1 = new Run();

            RunProperties runProperties1 = new RunProperties();
            FontSize fontSize4 = new FontSize() { Val = 11D };
            Color color4 = new Color() { Rgb = "0A0A09" };
            RunFont runFont1 = new RunFont() { Val = "Calibri" };
            FontFamily fontFamily1 = new FontFamily() { Val = 2 };
            FontScheme fontScheme5 = new FontScheme() { Val = FontSchemeValues.Minor };

            runProperties1.Append(fontSize4);
            runProperties1.Append(color4);
            runProperties1.Append(runFont1);
            runProperties1.Append(fontFamily1);
            runProperties1.Append(fontScheme5);
            Text text1 = new Text();
            text1.Text = "Requested by John S. (regular officer) - 20.10.19,";

            run1.Append(runProperties1);
            run1.Append(text1);

            Run run2 = new Run();

            RunProperties runProperties2 = new RunProperties();
            FontSize fontSize5 = new FontSize() { Val = 11D };
            Color color5 = new Color() { Rgb = "4A79B1" };
            RunFont runFont2 = new RunFont() { Val = "Calibri" };
            FontFamily fontFamily2 = new FontFamily() { Val = 2 };
            FontScheme fontScheme6 = new FontScheme() { Val = FontSchemeValues.Minor };

            runProperties2.Append(fontSize5);
            runProperties2.Append(color5);
            runProperties2.Append(runFont2);
            runProperties2.Append(fontFamily2);
            runProperties2.Append(fontScheme6);
            Text text2 = new Text() { Space = SpaceProcessingModeValues.Preserve };
            text2.Text = "Approved by Franchesco N. (supervising manager) - 22.10.19,";

            run2.Append(runProperties2);
            run2.Append(text2);

            Run run3 = new Run();

            RunProperties runProperties3 = new RunProperties();
            FontSize fontSize6 = new FontSize() { Val = 11D };
            Color color6 = new Color() { Rgb = "728D3C" };
            RunFont runFont3 = new RunFont() { Val = "Calibri" };
            FontFamily fontFamily3 = new FontFamily() { Val = 2 };
            FontScheme fontScheme7 = new FontScheme() { Val = FontSchemeValues.Minor };

            runProperties3.Append(fontSize6);
            runProperties3.Append(color6);
            runProperties3.Append(runFont3);
            runProperties3.Append(fontFamily3);
            runProperties3.Append(fontScheme7);
            Text text3 = new Text();
            text3.Text = "Signed by Koglovomor I. (CTO) - 22.10.19";

            run3.Append(runProperties3);
            run3.Append(text3);

            sharedStringItem1.Append(run1);
            sharedStringItem1.Append(run2);
            sharedStringItem1.Append(run3);

            sharedStringTable1.Append(sharedStringItem1);

            sharedStringTablePart1.SharedStringTable = sharedStringTable1;
        }

    }
}


text:
Q: Addresses of two char pointers to different string literals are same #include<stdio.h>
#include<string.h>

int main()
{
    char * p = "abc";
    char * p1 = "abc";
    printf("%d %d", p, p1);
}

When I print the values of the two pointers, it is printing the same address. Why?

A: Whether two different string literals with same content is placed in the same memory location or different memory locations is implementation-dependent.
You should always treat p and p1 as two different pointers (even though they have the same content) as they may or may not point to the same address. You shouldn't rely on compiler optimizations.
C11 Standard, 6.4.5, String literals, semantics

It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

The format for printing must be %p:
  printf("%p %p", (void*)p, (void*)p1);

See this answer for why.

A: String literals in the code are stored in a read-only data segment of the code. When you write down a string literal like "abc" it actually returns a 'const char*' and if you had all the compiler warnings on it would tell you that you are casting at that point. You are not allowed to alter those strings for the very reason you have pointed out in this question.

A: Your compiler seems to be quite clever, detecting that both the literals are the same. And as literals are constant the compiler decided to not store them twice.
It seems worth mentioning that this does not necessarily needs to be the case. Please see Blue Moon's answer on this.

Btw: The printf() statement should look like this
printf("%p %p", (void *) p, (void *) p1);

as "%p" shall be used to print pointer values, and it is defined for pointer of type void * only.*1

Also I'd say the code misses a return statement, but the C standard seems to be in the process of being changed. Others might kindly clarify this.

*1: Casting to void * here is not necessary for char * pointers, but for pointers to all other types.

A: When you create a string literal ("abc"), it is saved into a memory, which contains string literals, and then it's being reused if you refer to the same string literal, thus both pointers pointing to the same location, where the "abc" string literal is stored.
I've learned this some time ago so I might not have explained it really clearly, sorry.

A: This actually depends on which compiler you are using.
In my system with TC++ 3.5 it prints two different values for the two pointers i.e. two different addresses.
Your compiler is designed s.t it will check for existence of any value in the memory and depending on its existence it will reassign or use the same reference of the previously stored value if the same value is referred to.
So don't think about it too much as it depends on the way the compiler parses the code.
THAT'S ALL...

A: Your compiler has done something called "string pooling". You specified that you wanted two pointers, both pointing to the same string literal - so it only made one copy of the literal.
Technically: It should have complained at you for not making the pointers "const"
const char* p = "abc";

This is probably because you are using Visual Studio or you are using GCC without -Wall.
If you expressly want them to be stored twice in memory, try:
char s1[] = "abc";
char s2[] = "abc";

Here you explicitly state that you want two c-string character arrays rather than two pointers to characters.
Caveat: String pooling is a compiler/optimizer feature and not a facet of the language. As such different compilers under different environments will produce different behavior depending on things like optimization level, compiler flags and whether the strings are in different compilation units.

A: As others have said, the compiler is noticing that they have the same value, and so is deciding to have them share data in the final executable. But it gets fancier: when I compile the following with gcc -O
#include<stdio.h>
#include<string.h>

int main()
{
  char * p = "abcdef";
  char * p1 = "def";
  printf("%d %d", p, p1);
}

it prints 4195780 4195783 for me. That is, p1 starts 3 bytes after p, so GCC has seen the common suffix of def (including the \0 terminator) and done a similar optimisation to the one you have shown.
(This is an answer because it's too long to be a comment.)

A: because string "abc" itself a address in memory. when u write "abc" again it store same address

A: It is compiler optimization but forget optimization for portability. Sometime compiled codes are more readable than actual codes.

A: you are use string literal,
when complier catch two same string literal,
it give the same memory location,
therefore it show same pointer location./


text:
Q: Give Apache Permission To Folder I've installed Centos5, installed a web server and set up virtual host. The host is pretty much set up like this:
> adduser user1
> mkdir -p /home/user1/public_html/domain1.com/{public,private,log,cgi-bin,backup}
> chmod -R 755 /home/user1/public_html/

And I've added a VirtualHost entry in httpd.conf that looks like this:
<VirtualHost *:80>
#Blah blah blah
  DocumentRoot /home/user1/public_html/domain1.com/public
#Blah blah blah
</VirtualHost>

So apache can ready the directory just fine but has problems uploading files because the permission is denied. The scripting language is PHP.
How can I allow file uploads without making everything 777 permssion?

A: chown the directory to match Apache's configured username/groupname, and check where PHP is putting its uploads
Apache's user/group are defined by the User and Group .conf options, and PHP's upload dir is specified by the upload_tmp_dir .ini option.

A: make all folders 755 and change the owner to the user who is running apache. Usually in Centos should be httpd

A: upload files someplace other then the docroot


text:
Q: Detect endianness with type punning & padding bits Here is a common trick used to detect endianness at runtime, seen for instance in the C FAQ:
int x = 1;

if (*(char *)&x == 1)
{
  /* little-endian */
}
else
{
  /* big-endian */
}

According to my reading of the standard, it does not lead to an undefined behavior since it does not break the strict aliasing rule.
Anyway, as long as an integer type other than unsigned char can contain padding bits (such as x), couldn't the condition *(char *)x == 1 be wrong even if it is a little-endian system?
In that case, is the solution with unions better for doing this?

A: I'm not sure endianness really makes sense when you have padding bits, but the otherwise you are right and the condition might be wrong. At least you are not invoking undefined behavior as character types have no trap representations.
Otherwise what you can do is to use exact-width integer types (like uint32_t, etc.). Although these types are optional, they are guaranteed to have no padding bits.
For information, note that signed char also cannot have padding bits.


text:
Q: Javascript Test value in array I have a html table I an trying to create a function for. I will loop over all of the column names and if they contain a word that is in my array, I will turn that columns value into a formatted link accordingly.
function createLink(field, val){

    // Create a mapping of our data
    var output = {
        'ntid': 'https://example.com/profile/'+val,
        'email': 'mailTo:' + val
    };

    // Test and return values
    // pseudo code

    if(field matches a key partially in output){
        return ''+[val]+'';
    }else{
        return 'No Matches';
    }

}

 // Examples
 createLink('NTID', 'bob'); // 'bob';
 createLink('Sup NTID', 'bob'); // 'bob';
 createLink('Email', 'bob@example.com'); // 'bob@example.com';
 createLink('Sup Email', 'bob@example.com'); // 'bob@example.com';

How could I go about testing the value to see if it has a partial match in my output array and then returning its formatted link?
Since these column names are dynamic and could change any time, I just want to test for partial words rather than the exact string.
If there is no match, I could just return a placeholder value such as "No Match".

A: Iterate Object.keys and return if a key is in the "field" string:

function createLink(field, val) {

    var output = {
        'ntid': 'https://example.com/profile/' + val,
        'email': 'mailTo:' + val
    };

    for (var key of Object.keys(output))
        if (field.toLowerCase().includes(key))
            return `<a href="${output[key]}" target="_blank">${val}</a>`;

    return 'No Matches';
}

// Examples
console.log(createLink('NTID', 'bob'));
console.log(createLink('Sup Email', 'bob@example.com'));


text:
Q: how to loop table row and get the column checkbox Using ajax, how to:

*

*loop through each table row

*get the respective column checkbox value

*upon finish loop, store in database (refer to Database section below)

javascript/jquery

HTML

            Permission
            Read
            Create
            Edit
            Delete

                Product
                <input type="checkbox" class="big-checkbox" name="r[]"/>
                <input type="checkbox" class="big-checkbox" name="c[]"/>
                <input type="checkbox" class="big-checkbox" name="e[]"/>
                <input type="checkbox" class="big-checkbox" name="d[]"/>

                Invoice
                <input type="checkbox" class="big-checkbox" name="r[]"/>
                <input type="checkbox" class="big-checkbox" name="c[]"/>
                <input type="checkbox" class="big-checkbox" name="e[]"/>
                <input type="checkbox" class="big-checkbox" name="d[]"/>

                Quotation
                <input type="checkbox" class="big-checkbox" name="r[]"/>
                <input type="checkbox" class="big-checkbox" name="c[]"/>
                <input type="checkbox" class="big-checkbox" name="e[]"/>
                <input type="checkbox" class="big-checkbox" name="d[]"/>

                Banking
                <input type="checkbox" class="big-checkbox" name="r[]"/>
                <input type="checkbox" class="big-checkbox" name="c[]"/>
                <input type="checkbox" class="big-checkbox" name="e[]"/>
                <input type="checkbox" class="big-checkbox" name="d[]"/>

<button type="button" class="btn btn-primary" id="btnUpdPermission">Save</button>

HTML (screenshot)

Database table design

*

*file_id is the foreign key to the file master table (page that authorized user will access)

*user_id is the foreign key to the user master table (to whom this access is granted)

*rights r=read,c=create,e=edit,d=delete

A:
1.loop through each table row

You should use .each method in combination with children.
children method gets the children of each element in the set of matched elements, optionally filtered by a selector.
$('#table_perm tbody tr').each(function(){
      $(this).children('td').each(function(){

      });
});

2.get the respective column checkbox value

For this you can use find method.
$('#table_perm tbody tr').each(function(){
      $(this).children('td').each(function(){
         let checkboxValue = $(this).find('.big-checkbox').val();
      });
});

3.upon finish loop, store in database

For this, you can create an asynchronous call by sending all the information via AJAX or you can use a form by passing an action method from server-side.

A: If I understand it well, each row corresponds to permissions to one file master table, right? (identified by file_id in your database) If that's the case, first I'd put that id each table row (as an id, as a data-* field, etc.)...

    Product
    <input type="checkbox" class="big-checkbox" name="r[]"/>
    <input type="checkbox" class="big-checkbox" name="c[]"/>
    <input type="checkbox" class="big-checkbox" name="e[]"/>
    <input type="checkbox" class="big-checkbox" name="d[]"/>

    Invoice
    <input type="checkbox" class="big-checkbox" name="r[]"/>
    <input type="checkbox" class="big-checkbox" name="c[]"/>
    <input type="checkbox" class="big-checkbox" name="e[]"/>
    <input type="checkbox" class="big-checkbox" name="d[]"/>

...................

Then, considering your table structure, to loop your rows and get all the checkboxes values, one option could be...
var myPermissions = {};

$('#table_perm tbody tr').each(function() {

    var sectionId = $(this).data('id');
    var sectionPermissions = [];

    $(this).find('input.big-checkbox:checked').each(function() {
        sectionPermissions.push($(this).attr('name').charAt(0));
    });

    myPermissions[sectionId] = sectionPermissions.join(',');

});

So you finally get an object myPermissions with all permissions for each section...
{
    3: "r,c",
    4: "r,d",
    5: "c,e,d"
    ....
}

You can send that in your ajax call as a parameter.
NOTE: Two pieces of advice in your code...

*

*There's an error in your html, your closing td lines twice (		)

*If you're going to do this collecting data with ajax and not using a form, to avoid getting the permission letter from the string name, it would be better if you assign a value to each checkbox indicating the letter of that permission. I mean...
<input type="checkbox" class="big-checkbox" name="r[]" value="r"/>
<input type="checkbox" class="big-checkbox" name="c[]" value="c"/>
..........

... so then would be easier and cleaner to get the value...
sectionPermissions.push($(this).val());

I hope it helps


text:
Q: How to find whether a tree node has children I am trying to find a code for knowing whether the tree node
has children in Tkinter python 2.6. I tried with similar wxpython code but it fails!
This is for I wanted to do some programming with my ttk treeview widget, if I can get these details
like if there is any child node exists(True/False) or how many child node count then it is easy for me
to make "IF-Conditions" in my program.
Somebody please help me soon
Please note my code
childItems= self.tree.ItemHasChildren("Arithmetic")

print childItems

Error:

AttributeError: Treeview instance has no attribute 'ItemHasChildren'

A: I was looking for the same, and came up with this:
if tree.get_children([iid_of_the_active_selection]):
  pass

It works for single selection configuration (selectmode="browse").
Not sure if this is what you were looking for, but hope it helps.


text:
Q: Create a button that changes between red and green I want to create a simple button that changes between the colors red and green as I click them to indicate that something has been completed. Does anyone know of a simple way to get a button to change back and forth between colors? The setup of the page isn't how I want it yet but the button needs to be configured before I can format the rest of the page how I would like. I left out the CSS that deals with the body and other things like the headings.
Here is what I have so far after looking online for a while:

function colorChange(id) {
  var e1 = document.getElementById(id);
  var currentClass = el.getAttribute("class");
  if(currentClass == 'classA') {
    el.setAttribute("class", "classB");
  }
  else {
    el.setAttribute("class", "classA");
  }
}
#select {
    width: 10em;
    height: 1.5em;
}

.classA {
    background: red;
}

.classB {
    background: green;
}
<input type="button" id="select" onclick="colorchange('select')" class="classA" />

A: Here is the native JavaScript version. You first query the button directly with the getElementById selector. You then add an event listener, waiting for the click event.
The classList, although it returns an array, you can't use indexOf on it. However, you can use contains with it. It's also important to note that classList is not available in Internet Explorer 9 or earlier versions

var button = document.getElementById('my-button');

button.addEventListener('click', function() {
    if (button.classList.contains('red')) {
      button.classList.remove('red');
      button.classList.add('green');
      button.innerHTML = 'Done';
    }
    else {
      button.classList.remove('green');
      button.classList.add('red');
      button.innerHTML = 'Not Done';
    }
});
.green { background: green; }
.red { background: red; }
<button id='my-button' class='green'>Change Color</button>

This is best accomplished through jQuery and it's toggleClass function.

$('#my-button').on('click', function() {
  $(this).text($(this).hasClass('red') ? 'Done': 'Not Done');
  $(this).toggleClass('red');
  $(this).toggleClass('green');
});
.red { background: red; }
.green { background: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='my-button' class='red'>Change Color</button>

As you can see above, it's much easier in jQuery.

A: You only need to be more careful with your syntax. colorchange on your input vs colorChange in your JS (capital 'C') and and e1 is different to el (1 vs L).

function colorChange(id) {
  var el = document.getElementById(id);
  var currentClass = el.getAttribute("class");
  if(currentClass == 'classA') {
    el.setAttribute("class", "classB");
  }
  else {
    el.setAttribute("class", "classA");
  }
}
#select {
  width: 10em;
  height: 1.5em;
}

.classA {
  background: red;
}

.classB {
  background: green;
}
<input type="button" id="select" onclick="colorChange('select')" class="classA" />

A: Your logic is ok. Just you have to correct these typos:

*

*Change e1 to el ( L instead of 1 )

*Change onclick="colorchange('select')" to onclick="colorChange('select')"
Keep mind that you need to be more carefull, as the JavaScript is Case sensitive.
Have fun!


text:
Q: Selecting a value for resistor to make initial capacitor voltage a certain amount
In the above question, I found the amount of R1 to be 31.6k (R1 = 31.6KΩ) and I worked out R2 in this way:
5 * (R1 / (R1 + R2)) * R2  (first calculate the current in R2 branch and then use V = IR formula)
Which makes the R2 = 0.40001.
The book says that v(0-) = 5R2 (somehow short-circuiting R1).
Am I missing something here?


text:
Q: Splitting shapefile into separate shapefiles based on feature class using Arcmap 10.3?
I'm trying to split up this nested watersheds by name.  I want each watershed to be it's own shapefile.  Is there a faster way to do this besides highlighting each watershed and then exporting it?  I'm using Arcmap 10.3.

A: Arcpy is excellent for this. What you want is two loops: one to build a list of watersheds from the name field, and then one to select each watershed by turn, and then copy it to a new output shapefile.
Here's some code I wrote to solve this problem. It's intended as a custom script in the Toolbox, but you could modify it for one shot. Or feel free to bring it into the Toolbox if you want to use it for other projects.
I would also recommend looking through the ArcPy documentation - there are a lot of ways to automate the yak-shaving parts of GIS if you do your research.
import arcpy, time, os, traceback
from arcpy import env

#set parameters
# SplitFeat - input features
SplitFeat = arcpy.GetParameterAsText(0)
# SplitField - input field
SplitField = arcpy.GetParameterAsText(1)
# OutLocation - output folder
OutLoc = arcpy.GetParameterAsText(2)
#MaxSplit = Maximum number of files to create
MaxSplit = int(arcpy.GetParameterAsText(3))
# Overwrite output

#try loop
try:

    IndNum = 0

    arcpy.MakeFeatureLayer_management(SplitFeat, "Split_lyr")
    CatList = []
    CodeList = []
    FldList = (SplitField)
    with arcpy.da.SearchCursor("Split_lyr", SplitField) as cursor:
        for row in cursor:
            if row[0] not in CatList and IndNum < MaxSplit:
                AttString = str(row[0])
                print AttString
                CatList.append(AttString)
                CodeString = ''.join(e for e in AttString if e.isalnum())
                CodeList.append(str(CodeString))
                IndNum = IndNum + 1
            elif IndNum == MaxSplit - 1:
                arcpy.AddMessage(
                "{0} classes identified. Proceeding with script.".format(MaxSplit))
                break

    #splitting features
    #new iteration number
    IterNum = 0
    for Cat in CatList:
        CodeName = CodeList[IterNum]
        ClassName = CodeName[0:30]
        ClassFile = os.path.join(OutLoc, ClassName)
        arcpy.AddMessage("Creating file {0}...".format(ClassFile))
        #select by attributes
        SelClause = "{0!s} = '{1!s}'".format(SplitField, Cat)
        arcpy.SelectLayerByAttribute_management("Split_lyr", "NEW_SELECTION", SelClause)
        #Copy features, using CodeList index as key
        arcpy.Select_analysis("Split_lyr", ClassFile)
        #arcpy.CopyFeatures_management("Split_lyr", ClassFile)
        arcpy.AddMessage("{0} has been created.".format(ClassFile))
        IterNum = IterNum + 1

except Exception:
    e = sys.exc_info()[1]
    arcpy.AddError(e.args[0])
    arcpy.AddMessage("ERROR! \n Call Stack: " + traceback.format_exc())


text:
Q: Where is the flaw that led to the fallacy that $x^4 + y^4 = z^4$? Consider $x^2 + y^2 = r^2$. Then take the square of this to give $(x^2 + y^2)^2 = r^4$. Clearly, from this $r^4 \neq x^4 + y^4$.
But consider: let $x=a^2, y = b^2 $and$\,\,r = c^2$. Sub this into the first eqn to get $(a^2)^2 + (b^2)^2 = (c^2)^2$. $x = a^2 => a = |x|,$ and similarly for $b.$
Now put this in to give $|x|^4 + |y|^4 = r^4 => (-x)^4 + (-y)^4 = r^4 $ or $ (x)^4 + (y)^4 = r^4,$ both of which give $ x^4 + y^4 = r^4$
Where is the flaw in this argument?
Many thanks.

A: $x = a^2$ does not imply that $a = |x|$, rather $|a| = \sqrt{x}$.

A: The fact that $x=a^2$ is quite far to imply that $a=|x|$ (second paragraph).

A: Note that $(x^2+y^2)^2=r^4$ does not imply that $r^4\ne x^4+y^4$.
In fact, you show that $$a^4+b^4=c^4$$
provided $x^2+y^2=r^2, x=a^2, y=b^2, z=c^2$. So what?


text:
Q: Combining effect sizes to learn about the difference between two groups? I am interesting in learning if there is difference between the control and the treatment group in a paper I am reading. Unfortunately the paper only compares the respective conditions to a 0 effect size. The paper does not have open data or report standard deviations.
The relevent results reported in the paper are:

A one-sample t test on the recommended IAT measure indicated that the mean D score for the participants in the control condition (M = −.19 was significantly less than zero, t(29) = −2.50, p = .019. The estimated Cohen's d for this effect was .46. In contrast, a one-sample t test indicated that the mean D score for the participants in the perspective taking condition (M = −.13) was not significantly less than zero, t(29) = −1.61, p = .119.

Is it possible to compare the two effect sizes to learn about the difference between the two conditions instead?

A: I assume that what you are interested in is the difference in differences. Simply differencing the mean D for the treatment and control is this value (i.e., -.19 - (-.13) = -.06). You can compute a t-test on this difference by recovering the standard deviations of the difference scores from the t-value:
$$ s_D = \sqrt{\frac{M_D^2 N}{t^2}} . $$ For the control group, this is:
 $$ s_D = \sqrt{\frac{-.19^2(30)}{-2.50^2}} = 0.416 . $$
For the treatment group this is:
 $$ s_D = \sqrt{\frac{-.13^2(30)}{-1.61^2}} = 0.442. $$
With these values, you can compute a t-test comparing these two mean difference scores:
$$
t = \frac{M_{D_{Tx}} - M_{D_{Cg}}}{
\sqrt{
\left(\frac{ s_1^2(N_1 - 1) + s_2^2(N_2 - 1)}{N_1 + N_2 - 2}\right)
\left(\frac{N_1 + N_2}{N_1N_2}\right)
}  } ,
$$
$$
t = \frac{-0.19 - (-0.13)}{
\sqrt{
\left(\frac{ 0.442^2(30 - 1) + 0.416(30 - 1)}{30 + 30 - 2}\right)
\left(\frac{30 + 30}{30(30)}\right)
}  } = -0.1397 .
$$
This is a more meaningful test of any treatment effect and is the interaction in a 2 by 2 split-plot ANOVA (time by treatment).
Note that the authors computed Cohen's d as the mean difference divided by the standard deviation of the mean difference. A more standard Cohen's d for paired data is to divide by either the pre-test standard deviation or both the pooled pre and post-test standard deviations. Dividing by the standard deviation in differences is standardizing change relative to variability in change across people rather than simply variability in the measure across people. I think that the latter is far more interpretable.


text:
Q: How to efficiently resize image with antialias? I try to resize an image like this:
aPaint.setAntiAlias(true); // Enabling this flag will cause all draw operations that support antialiasing to use it.
aPaint.setFilterBitmap(True); // enable bilinear sampling on scaled bitmaps. If cleared, scaled bitmaps will be drawn with nearest neighbor sampling, likely resulting in artifacts.
apaint.setDither(true); // Enabling this flag applies a dither to any blit operation where the target's colour space is more constrained than the source.
aCanvas.drawBitmap(aBitmap, aJSrcRect, aJDestRectf, apaint);

But I don't have a very good antialised image (it's antialiased, but not very good). Here is an image showing my problem

What can i do to increase the quality of the antialias under android ?

A: For antialias effect, you can try to create a Paint like this:
Paint paint= new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);

Finally apply paint on canvas with:
canvas.drawBitmap(mBitmap, 0.f, 0.f, paint)


text:
Q: SQL Server, Multiple Conditions in correlated subquery I tried to use compound conditions in the correlated subquery, but it didn't return the result expected. Can you look into the example below to see why the first query doesn't work out but the second query works out?
Create table & populate rows:
CREATE TABLE TestCase
(
    Seq INT IDENTITY PRIMARY KEY,
    ID INT,
    Name VARCHAR(50)
)

INSERT INTO TestCase
VALUES
(100, 'MJ'),
(110, 'MJ'),
(120, 'AK'),
(130, 'AK')

First query:
SELECT A.ID, A.Name FROM TestCase AS A
WHERE A.ID IN (SELECT ID FROM TestCase WHERE ID <> A.ID AND Name = A.Name)

(0 row(s) affected)
Second query with EXISTS:
SELECT A.ID, A.Name FROM TestCase AS A
WHERE EXISTS (SELECT ID FROM TestCase WHERE ID <> A.ID AND Name = A.Name)

(4 row(s) affected)
Supposedly, both queries should return all four rows but the first one did not; I am not sure why only the second query returned four rows. Can someone help? Thank you.

A: The reason the first query is returning 0 records is because you are trying to match the row's ID to the rows returned by the subquery, A.ID IN (...), but the subquery correlates to exclude all ID's equal to the current record (A.ID<>ID). So, the WHERE IN clause will always evaluate to false.
The second query is not trying to match the returned rows with A.ID, but only that there exists a row with a different ID but with the same name.


text:
Q:   displays a tiny line when I make   in my site, it displays a tiny line, which can be hidden on some elements because I'm usually using them on CSS buttons, but I have an if statement that says if this show the result if not show a non breaking space.
How do you reset the   to display nothing?

A: Is this tiny line an outline? Try this in css:
outline:none;

Is this tiny line an underline? Try this in css:
text-decoration:none;

Is that something else, elaborate your question.

A: The "tiny line" is most likely an underline/border. Remove text-decoration and/or borders.
Why are you using  s if you don't want them to do anything, though? No need to clutter the source with them unless you really need them.


text:
Q: Properties under ARC: Always or public-only? After reading an article humbly named "The Code Commandments: Best Practices for Objective-C Coding" by Robert McNally a little less than two years ago, I adopted the practice of using properties for pretty much every data member of my Objective-C classes (the 3rd commandment as of may 2012). McNally lists these reasons for doing so (my emphasis):

*

*Properties enforce access restrictions (such as readonly)

*Properties enforce memory management policy (strong, weak)

*Properties provide the opportunity to transparently implement custom setters and getters.

*Properties with custom setters or getters can be used to enforce a thread-safety strategy.

*Having a single way to access instance variables increases code readability.

I put most of my properties in private categories, so number 1 and 4 are usually not issues I run in to. Arguments 3 and 5 are more 'soft', and with the right tools and other consistencies they could become non-issues. So finally, to me the most influential of these arguments was number 2, memory management. I've been doing this ever since.
@property (nonatomic, strong) id object; // Properties became my friends.

For my last few projects I've switched to using ARC, which made me doubt whether creating properties for pretty much anything is still a good idea or maybe a little superfluous. ARC takes care of memory managing Objective-C objects for me, which for most strong members works fine if you just declare the ivars. The C-types you had to manually manage anyway, before and after ARC, and the weak properties are mostly public ones.
Of course I still use properties for anything that needs access from outside of the class, but those are mostly only a handful of properties, while most data members are listed as ivars under the implementation header
@implementation GTWeekViewController
{
    UILongPressGestureRecognizer *_pressRecognizer;
    GTPagingGestureRecognizer *_pagingRecognizer;
    UITapGestureRecognizer *_tapRecognizer;
}

As an experiment I've been doing this a bit more rigorously, and the move away from properties for everything has some nice positive side effects.

*

*Data member code requirements (@property/@synthesize) shrunk down to just the ivar declaration.

*Most of my self.something references cleaned up to just _something.

*It's easily distinguishable which data members are private (ivars) and which are public (properties).

*Lastly, it 'feels' more like this was the purpose Apple intended properties for, but that's subjective speculation.

On to the question: I'm slowly sliding towards the dark side, using less and less properties in favor of implementation-ivars. Can you provide me with a bit of reasoning for why I should stick to using properties for everything, or confirm my current train of thoughts as to why I should use more ivars and less properties only where needed? The most persuasive answer for either side will receive my mark.
EDIT: McNally weighs in on Twitter, saying: "I think my main reason for sticking with properties is: one way to do everything, that does everything (including KVC/KVO.)"

A:
Can you provide me with a bit of reasoning for why I should stick to
  using properties for everything, or confirm my current train of
  thoughts as to why I should use more ivars and less properties only
  where needed?

Right now, I think it's fair to say that it's mostly a matter of style. As you say, the memory management benefit of properties is less important with ARC. On the other hand, the "benefits" of going back to direct ivar access aren't very compelling either:

*

*A @property declaration is quite similar to an ivar declaration. Avoiding the @synthesize directive doesn't seem like a big win -- we're not talking about a lot of code.

*The foo.something syntax is arguably a lot better than _something. Property access syntax is obviously designed to look like and work like C's dot syntax for accessing members of a structure. Being explicit about which object you're accessing (whether that's self or something else) is helpful. (Some people -- not me! -- advocate self->something for ivar access for this reason.) The leading underscore convention for ivars is fine, but it's not used consistently by all Objective-C code.

*Properties seem a better choice for accessing data stored in other objects of the same class (which is allowed under "private" access) and for access by subclasses (like C++'s "protected"). So the 'properties == public' idea is somewhat blurry.

*My sense is that properties were intended to simplify memory management and provide some other benefits. As you say, with the memory management benefit decreased, properties seem less compelling.
The path you've chosen -- going back to direct ivar access for internal data -- seems like a very reasonable choice and there's no obvious reason to change your course. But sticking to properties is also quite reasonable -- the drawbacks aren't significant, and there are some nice benefits like KVO compliance and a more consistent member access style.
Properties weren't the last step in the evolution of Objective-C, and I don't expect that ARC will be either. I don't have any specific information, but it seems like a good guess that additional features might be added at some point that make properties either more compelling or less so. We'll have to wait and see what happens.

A: I've also been pondering on this question. In my humble Opinion, only using properties for accessors makes the code much more readable. You can immediately see what variables are meant to be accessed publicly. And personally, always typing @property (...) in front of a variable is time consuming.


text:
Q: How to add server connection timeout using select()? I want to add a timeout to connect to a server because if the server is switched off my application stops working and starts waiting for the server reply for 1 minute. I want to stop trying to connect to the server after a fixed amount of time. They say that I should use select(), but I do not understand how to integrate it in a code below:
    int client;
    bool isExit = false;
    int fileSize = 0;
    int size = 0;
    int bufsize = 1024;
    char buffer[bufsize];

    string fileEnd = "<EOF>";

    string modelFolder = currentModelFolder;

    replace(modelFolder.begin(),
            modelFolder.end(),
            ';',
            '/');

    string requestStructure = modelFolder + "/" + currentFileName + "/" + fileEnd + "|" + '\0';

    char *bytes = new char[requestStructure.length()];
    memcpy(bytes, requestStructure.data(), requestStructure.length());

    sockaddr_in server_addr;

    client = socket(AF_INET, SOCK_STREAM, 0);

    if (client < 0)
    {
        cout << "Error establishing socket..." << endl;
        exit(1);
    }
    else
        cout << "Socket client has been created..." << endl;

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(serverPort);
    inet_aton(serverIp.c_str(), &server_addr.sin_addr);

    if (connect(client, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0)
    {
        cout << "=> Connection to the server port number: " << serverPort << endl;
    }

    // отправка запроса на сервер (сервер, данные, размер пакета)
    send(client, bytes, bufsize, 0);
    cout << "=> Awaiting confirmation from the server..." << endl;

    // получение данных с сервера (сервер, массив байтов, размер пакета)
    recv(client, buffer, bufsize, 0);
    cout << "Buffer = " << buffer << endl;

    int bufferStringSize = sizeof(buffer);
    string bufferSize = convertToString(buffer, bufferStringSize);

    stringstream stringToIntStream;
    stringToIntStream << bufferSize;
    stringToIntStream >> fileSize;

    ostringstream stepFilePathStructure;
    stepFilePathStructure << saveFolderPath << currentFileName << "";

    string stepFilePath = stepFilePathStructure.str();

    remove(stepFilePath.c_str());

    ofstream stepFile;
    stepFile.open(stepFilePath);

    while (size < fileSize)
    {
        int received = recv(client, buffer, bufsize, 0);

        stepFile.write(buffer, received);

        size += received;
    }

    close(client);


text:
Q: Tektronix function generator THD I am confused by the datasheet of the AFG3021C: https://www.tek.com/link-click-count?nid=75006&url=https%3A//download.tek.com/datasheet/AFG3000C-Arbitrary-Function-Generator-Datasheet-75W282817.pdf
I am interested in the THD of a generated sine wave, but the data sheet specifies THD as less then 0.2% and harmonic distortion as <-40 dBc, which just doesn't add up to me.
What is the difference between harmonic distortion and THD? What I am interested in is the RMS of the harmonics divided by the RMS of the fundamental.

A: The THD is listed for frequencies up to 20 kHz, whereas the harmonic distortion is given up to higher frequencies. I suspect this is for audio vs RF/analog testing. In the former, people tend to talk about THD, in the case of the latter, they tend to talk about the level of the harmonic with respect to the carried in dBc.
The RMS value of a sine wave is just the peak divided by \$\sqrt{2}\$, so the ratio between the peaks is identical to the ratio between the RMS values.

A: dBc is for sine wave and is  -60 dBc for the AFG3011C and -70 dBc for the higher model sampling rates.
Jitter affects dBc on sine carriers with two sidebands each -6dB lower than THD.
Thus -60 dBc = -54 dB THD
e.g.
http://thewelltemperedcomputer.com/Lib/Troisi.pdf

A: I found the answer.
First I managed to found this: https://download.tek.com/manual/AFG3000C-and-AFG3000-Specifications-and-Performance-Verification-077069102_Rev-B.pdf
Based on this, I got the idea, that the harmonic distortion isn't actually what I (we) though it was at all. It is in fact the level under which all harmonics are supposed to be.
Then I got confirmation from Tektronix:

The Harmonic Distortion Test specifies that each Harmonic of the
  Fundamental stays below a certain level in dBc for the corresponding
  frequency range.
Please note, that if all harmonic components are equal or less than
  -62 dBm, the THD will be smaller than 0,2%. This value does not directly correlate with the Harmonic Distortion values from the
  datasheet.


text:
Q: How to control fan speed on Acer V3-571G Speed fan, Gpu Tweaker any many more do not detect any fans on my laptop. How can I gain control above them? My computer is getting warm really fast and I would like to do something about that.
Acer V3-571g
i3-3110
GeForce GT630
Full specs: http://wklej.org/id/900178/
EDIT:
Fans are quiet now, but when I go into the game they go fast. I am not sure that I did not screw up fan settings earlier, but I do not know what programm I usedThe issue is that when I play for example Dirt 3 after one race computer is heating to much so  or even menu starts to go low on fps(like 15, and on cool 30-35->I checcekd it outside on cold wheather everything worked smooth all the time). The BIOS does not have these settings, unfortunatelly there is not much to do in this version of BIOS. I would like to speed up the fan. This is new computer(1.5 months now) but it got worse in a day.

A: Are the fans running on high now?   Most laptops do a decent job of running the fans fast when they are warm,  most users use a Fan utility to SLOW the fans to reduce noise.
If your laptop is warmer than it used to be,  I'd check that the vents are clean.  I've seen more overheating laptops that were due to dirt on the heatsink or clogged vents than I have due to a bad sensor that failed to turn the fans on.


text:
Q: How to Generate PDF from various page templates with ReportLab? I have JSON file with lots of data and four PDF templates for pages. I need to generate single PDF file with all this data ang page templates. Now my code looks like this:
    self.line(self.data['sendr'], 10, 250,
              250, {'min_font': 7, 'max_string': 70})
    self.line(self.data['list_num'], 10, 450,
              25, {'min_font': 7, 'max_string': 70})
    self.line(self.data['send_date'], 10, 250,
              45, {'min_font': 7, 'max_string': 70})
    self.line(self.data['delivery_rate_sum_end'], 10, 450,
              450, {'min_font': 7, 'max_string': 70})

    self.can.save()
    self.packet.seek(0)

    new_pdf = PdfFileReader(self.packet)
    current_folder = os.path.dirname(os.path.abspath(__file__))
    existing_pdf = PdfFileReader(
        file("{0}/original/blank_103_1.pdf".format(current_folder), "rb"))
    output = PdfFileWriter()

    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
    print "Page 1 complete"

    # four row page mail part
    for item in range(3, int(self.data['email_count']) - 2, 4):
        self.line(self.data['sends'][item]['rcpn'], 10, 350,
                  250, {'min_font': 7, 'max_string': 70})
        self.line(self.data['sends'][item]['mail_count'], 10, 450,
                  250)

        new_pdf2 = PdfFileReader(self.packet)
        existing_pdf2 = PdfFileReader(
            file("{0}/original/blank_103_2.pdf".format(current_folder), "rb"))

        page2 = existing_pdf2.getPage(0)
        page2.mergePage(new_pdf2.getPage(0))
        output.addPage(page2)
        print "Page ", item, " complete"

    # last page part
    self.line(self.data['sendr'], 10, 100,
              25, {'min_font': 7, 'max_string': 70})
    self.line(self.data['list_num'], 10, 70,
              45, {'min_font': 7, 'max_string': 70})
    self.line(self.data['send_date'], 10, 150,
              45, {'min_font': 7, 'max_string': 70})
    self.line(self.data['delivery_rate_sum_end'], 10, 450,
              450, {'min_font': 7, 'max_string': 70})

    new_pdf1 = PdfFileReader(self.packet)
    existing_pdf1 = PdfFileReader(
        file("{0}/original/blank_103_4.pdf".format(current_folder), "rb"))

    page1 = existing_pdf1.getPage(0)
    page1.mergePage(new_pdf1.getPage(0))
    output.addPage(page1)
    print "Last page complete"

    filename = int(time.time())
    outputStream = file(
        "{0}/pdf/f103/{1}.pdf".format(current_folder, filename), "wb")
    output.write(outputStream)
    outputStream.close()

It generates a single PDF file with all needed templates for pages but on all pages data rendered from the part for the first page. How can I spread data for every page only(some line-for page 1, some data-for page 2,3,..,n, some data-for last page)?


text:
Q: App Engine Python runtime doesn't bring same result as local I have a Python standard project on App Engine. It uses ast module to convert Python source code to another language's code. I faced the issue which wasn't caused in the local environment (Python 3.7.4 on macOS 10.15.4). The re-deployment had been successful, but the API wouldn't be updated. Creating another project with the same files didn't work properly. I also tried Cloud Shell by uploading the files or python3 main.py on local, then these were correct. Does Python runtime on App Engine have some differences?
Details:
Let py3ca.py read Python source code below as input on the local environment ($ python3 py3ca.py fizzbuzz.py).
# fizzbuzz.py
res = []
for i in range(1, 101):
    if (i % 15) == 0:
        res.append('Fizz Buzz ')
    elif (i % 3) == 0:
        res.append('Fizz ')
    elif (i % 5) == 0:
        res.append('Buzz ')
    else:
        res.append(i)
print(res)

This produces:
[
  [1, [], "#", "0_18"],
  [1, [], "=", ["var", "res"], [[]]],
  [1, [], "for range", "i", [1, 101]],
    [2, [], "ifs"],
      [3, [], "if", ["==", ["%", ["var", "i"], 15], 0]],
        [4, [], "call", null, ["attr", "res", "append"], ["Fizz Buzz "]],
      [3, [], "elif", ["==", ["%", ["var", "i"], 3], 0]],
        [4, [], "call", null, ["attr", "res", "append"], ["Fizz "]],
      [3, [], "elif", ["==", ["%", ["var", "i"], 5], 0]],
        [4, [], "call", null, ["attr", "res", "append"], ["Buzz "]],
      [3, [], "else"],
        [4, [], "call", null, ["attr", "res", "append"], [["var", "i"]]],
  [1, [], "call", null, ["var", "print"], [["var", "res"]]],
  [1, [], "end"]
]

However, Apps Script which sends to the App Engine produces:

This doesn't match with the local (lines 8, 10, 12).


text:
Q: Auto checkin a directory of Git I realize there are very good reasons I should not be doing this. However, given that I'm stupid, what is the best way to do the following.
I am using a directory in my git repo basically as a key value store. Where the filename is the key, and the value is the contents of the file.
I want, on every git commit, for files in this directory to be automatically added into the repo.
How should I solve this?
Thanks!

A: If I understand your problem correctly, you want something like SparkleShare, it lets you use a Git repository for filesharing and automaticly synchronizes your repository folder :)

A: So basically you want to git add the directory everytime you do a commit? You can use git hooks for that, take a look at Customizing Git - Git Hooks, pre-commit hook more specifically.


text:
Q: How to jump into python code in c++ call through GDB debugger? I have a C++ project which was written by others, which calls python code at the end of the execution.
In the C++ initializer, it defines a pHandle:
pHandle_ = PyObject_CallObject(pLoad_, NULL);
PyGILState_Release(gstate);

Then it calls python code this way:
PyObject *pyValue = PyObject_CallObject(pProcess_, pArgs);

pProcess_ and pArgs are created earlier. The python code's file name is 'runLogic.py' and the function executed in runLogic.py is 'process()'.
Is there a way to break into the python's process() function while I debug in c++ through GDB?  In C++ code, I can step through until the line above, copied again below:
PyObject *pyValue = PyObject_CallObject(pProcess_, pArgs);
Then I don't  know how to jump into the  Python's function.
Is there a way to do that? I want to trace the full logic of the  code, in addition to C++'s code.

A:
Then I don't know how to jump into the Python's function.

Presumably you want to now step through Python code.
GDB doesn't know how to do that, but pdb can.
Assuming you can modify runLogic.py, add import pdb to the top of the file, and pdb.set_trace() in the process() function.
This will let you step through Python code. If you have breakpoints in C++, and Python code calls back into C++, these breakpoints will still be active, you should be able to debug both C++ and Python.


text:
Q: using WPF Caliburn, How do I change datagrid binding based on the combobox selection? about to add the following features

If select this combobox, I want to change the itemssource of the datagrid.
Are there any examples related to this?

A: You can do the following:

*

*Create a WPF project.

*Create a view (xaml) with the combobox and datagrid inside it.

*Create a view model for this newly created view and declare public properties (collection/list) for the ItemsSource of the combobox and the grid. Also have a property for the selected item of the combobox.

*Set this view model as the data context of your view.

*In the setter of the combobox's selected item - change the property which is bound to the datagrid's ItemsSource to the collection that you by calling a method or however you wish.

A: I did this:
Add the namespace for caliburn in xaml
xmlns:cal="http://www.caliburnproject.org"

Here is the combobox:
<ComboBox ItemsSource="{Binding ComboBoxItemSource}" SelectedItem="{Binding SelectedItem}" cal:Message.Attach="[Event SelectionChanged] = [ComboBoxSelectionChanged()]" />

and the viewmodel should be having this method:
public void ComboBoxSelectionChanged()
    {
        // here based on the SelectedItem you can change the ItemSource for the dataGrid.
    }

Whenever you are changing the selectedItem of Combobox the method will get hit and based on the logic that you need you can assign the ItemSource for the dataGrid.
Hope this helps :)


text:
Q: Is it legit to safe instances of a class in a public static list to use them globally? while writing a new project in C# I created a public static list that contains all the dynamically created instances. Let me give u some code to clarify what i mean.
class myClass
{
    public static List<myClass> ListForGlobalUse = new List<myClass>();

    public myClass()
    {
        ListForGlobalUse.Add(this);
    }
}

I did this because I needed the instances in other classes and I think that it is more handy and easier to read than creating a List in each class.
Now I am curious if this is legit or if this could be (for any reason) a bad habit.
Maybe someone could also explain how it influences the assembler code since static objects and the methods are allocated in a different place in memory than the dynamic objects.
Maybe i chose the wrong tag but I really don't know which fits the best.

A: It is legit, no lawyer can sue you for it.
However, it's really just a global object, and those are too easy to use everywhere, tangling up and cabling everything in your code together.
You save some writing work in the beginning, but in the longer term the probability gets higher and higher that you'll regret your super tight coupling.
You can always pass objects down the call-tree, as parameters to constructors or functions. And if some class is the only user of an object, then only that class should know about or own it.

Personal statement:
I don't remember a single situation in at least the last 10 years where I needed a global object; the nice effect is I never had any of the problems related to this worst kind of coupling.

Example:
Let's say you have a database connection; call it mongoConnection:
global:
    MongoDB mongoConnection

You also have a getCustomers function in your business model:
business-module:
    getCustomers (arguments)
        ... mongoConnection.fetch("customers") ...

However, someone hasn't read how mongoConnection should be used, but because she/he/it is familiar with MongoDB, she/he/it considers it not a problem and now uses it everywhere:
// core.cs
mongoConnection.fetch("customers")

// misc.cs
mongoConnection.fetch("customers")

// foobar.cs
mongoConnection.fetch("cutsomers")

// api/web/authentication/local/core/foo/bar/core.cs
mongoConnection.fetch("customers")

So instead of using your clean Customers-API, you have now spread implementation details all over, just because someone knew MongoDB better than the Customers-API.
No problem for the moment.
But in three months you realise your definition of customers was bad. You rename it to users and change the names of all fields.
You do a global search-and-replace:
// core.cs
mongoConnection.fetch("users")

// misc.cs
mongoConnection.fetch("users")

// foobar.cs
mongoConnection.fetch("cutsomers")

// api/web/authentication/local/core/foo/bar/core.cs
mongoConnection.fetch("users")

And then you go manually through the code, adjusting all the queried fields. That's a crapton of work in a medium sized project. After your changes, you release your code.
Three months later, a customer complaints that the heavily advertised Foobar module isn't working; how can that be, it all compiled.
You debug, and fix ...
// foobar.cs
mongoConnection.fetch("users") // fix: not cutsomers, but users

... and release. The customer calls again, calling you a fraud and an idiot. He now wants his money back.
Hmm. Oh crap, you forgot to also adjust all the renamed fields in the foobar-module. You fix that. You sweet-talk to the customer for hours.
You then decide to add unit-testing so something like that does not happen again. It all works fine, you have nightly testing and everything.
Three months later, your application has grown to 100 KLoC with tests now running for hours, making them useless for manual programmer use. Also your testing database is full. You realise it would be better to run the tests on mock-database-connections that do just what is required by the tests.
Now remember you have direct database connections spread everywhere, in approximately 121 source files. Many of those source files are passing the database-connection through to some plugins written in a "special" style by a guy who has left the company.
Some of your customers are now demanding important features, and you haven't got the workforce required to improve your testing procedure.
Three months later.
You grow and grow, and once again realise that your Users datastructure should be modified, or else your application can't scale enough to serve some of your key-customers ...
Your application has grown to 269 files. Connections spread everywhere. Some plugins now use plugins on their own ... your connection is a virus and it feels like it begins living. Some modules modify the caching parameters and forget to reset them, other modules ask really nonperformant queries that should have never been asked ...
Customers want more features ... You hire more MongoDB experts, and all of them find your connection familiarohmygod.
The night before christmas, a customer call.
"You frantic burglar, your crappy module is buggy as shit and my most important campaign generating 94% of annual sales is just missing its peak I hope you die because my employees will now starve and ..."
And you question your decision to use globals.

A: You can use the Object Pool pattern: http://sourcemaking.com/design_patterns/object_pool
This a good implementation in c#: https://stackoverflow.com/a/2572919/3437025


text:
Q: Check if dll launched from another application is already open I work with an application (lets say application A) that I write add on modifications for.
The application A has functionality to allow scripts to call class librarys or exe files.
It works by taking a parameter object created by the application A and passes it into the class library (lets call it Application B)
Application A is pretty much a black box that I have no idea what the code looks like or does.
I have a script format that takes a parameter object from application A (containing relevant information about the calling program, for example: current user, user language, item application B was launched from etc etc) and passes it into application B. This script functionality is set up using a Administrator panel that is part of application A.
The launcher script must use form.Show() and not form.ShowDialog() to open application B as the user must be able to access application A while application B is open (Data checking and so forth).
Now I want to be able to prevent application B from opening multiple times as is currently possible, because it has been launched using form.Show() and not form.ShowDialog() however I can't seem to find a suitable way to do this.
I firstly tried checking the current processes but have found that application B is not listed here as it is launched by the application A.

*

*M3 Sales Automation is Application A

*New Customer is Application B

This can be seen from the following screen shots from my task manager:

Both M3 Sales Automation and New Customer are listed in the applications section, but only M3 Sales Automation is listed in the processes section.
Initially I tried accessing the processes but found that as its not actually listed there I can't check that and had to look a little deeper. Now I did some more checking and found that the NewCustomer.dll is listed in the ProcessModules for the current process.
I used the following code in the launcher script to get the information:
        public void GetProcessModules()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            string modulesOutput = string.Empty;
            foreach (ProcessModule pm in processModuleCollection)
            {
                modulesOutput += pm.ModuleName + ";\r\n";
            }

            MessageBox.Show(modulesOutput, "Modules");
        }

This outputted a long list of dll's that are part of application A. Now I thought that I could perphaps look to see if the NewCustomer.dll was listed more than once and if this occurred then prevent launch of the application as it would already be open. This was not the case however and the NewCustomer.dll is only listed once no matter how many times it is open.
So now my next thought is to look and see if I can access what is shown in the Task Manager Applications Tab. If my program is listed there then I want to prevent it opening again.
Does anyone have any Idea how to acheive this?
I'm not even sure what I should be searching for as everytime I try to search I get answers talking about looking in the Processes which is not relevant here.

A: In Application tab in Windows Task Manager you see the list of windows opened in the system, but there is only one process (1 application) wich onws the 2 windows.
This code is for search a window in the system. Maybe is useful for you because you can search by "New Customer" title or maybe it's a good start for your future research.
using System.Runtime.InteropServices;
using System.Text;

public class WndSearcher
{
    public static IntPtr SearchForWindow(string wndclass, string title)
    {
        SearchData sd = new SearchData { Wndclass=wndclass, Title=title };
        EnumWindows(new EnumWindowsProc(EnumProc), ref sd);
        return sd.hWnd;
    }

    public static bool EnumProc(IntPtr hWnd, ref SearchData data)
    {
        // Check classname and title
        // This is different from FindWindow() in that the code below allows partial matches
        StringBuilder sb = new StringBuilder(1024);
        GetClassName(hWnd, sb, sb.Capacity);
        if (sb.ToString().StartsWith(data.Wndclass))
        {
            sb = new StringBuilder(1024);
            GetWindowText(hWnd, sb, sb.Capacity);
            if (sb.ToString().StartsWith(data.Title))
            {
                data.hWnd = hWnd;
                return false;    // Found the wnd, halt enumeration
            }
        }
        return true;
    }

    public class SearchData
    {
        // You can put any dicks or Doms in here...
        public string Wndclass;
        public string Title;
        public IntPtr hWnd;
    }

    private delegate bool EnumWindowsProc(IntPtr hWnd, ref SearchData data);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, ref SearchData data);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
}

Then you'd call:
// If you're viewing this page with IE, this *should* return the hwnd of the browser
IntPtr hWnd = WndSearcher.SearchForWindow("IEFrame", "pinvoke.net: EnumWindows");

Code from pinvoke.net.

A: Actually after looking at the code jlvaquero posted above I found the following on the same site
EnumDesktopWindows (user32)
I added the following using statements to my laucher script:

*

*using System.Text;

*using System.Runtime.InteropServices;
I then added the following class to my launcher script
    /// <summary>
/// EnumDesktopWindows Demo - shows the caption of all desktop windows.
/// Authors: Svetlin Nakov, Martin Kulov
/// Bulgarian Association of Software Developers - http://www.devbg.org/en/
/// </summary>
public class user32
{
    /// <summary>
    /// filter function
    /// </summary>
    /// <param name="hWnd"></param>
    /// <param name="lParam"></param>
    /// <returns></returns>
    public delegate bool EnumDelegate(IntPtr hWnd, int lParam);

    /// <summary>
    /// check if windows visible
    /// </summary>
    /// <param name="hWnd"></param>
    /// <returns></returns>
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsWindowVisible(IntPtr hWnd);

    /// <summary>
    /// return windows text
    /// </summary>
    /// <param name="hWnd"></param>
    /// <param name="lpWindowText"></param>
    /// <param name="nMaxCount"></param>
    /// <returns></returns>
    [DllImport("user32.dll", EntryPoint = "GetWindowText",
    ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);

    /// <summary>
    /// enumarator on all desktop windows
    /// </summary>
    /// <param name="hDesktop"></param>
    /// <param name="lpEnumCallbackFunction"></param>
    /// <param name="lParam"></param>
    /// <returns></returns>
    [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
    ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam);
}

I then added the following function in my launch script to call the new class and do the processing to discover the active windows
/// <summary>
    /// Checks if application window open.
    /// </summary>
    /// <returns></returns>
    private static bool IfApplicationWindowOpen(string windowName)
    {
        List<string> collection = new List<string>();
        user32.EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
        {
            StringBuilder strbTitle = new StringBuilder(255);
            int nLength = user32.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
            string strTitle = strbTitle.ToString();

            if (user32.IsWindowVisible(hWnd) && string.IsNullOrEmpty(strTitle) == false)
            {
                collection.Add(strTitle);
            }
            return true;
        };

        if (user32.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero))
        {
            foreach (string item in collection)
            {
                if (item.ToString().Equals(windowName))
                {
                    return true;
                    break;
                }
            }
        }
        return false;
    }

And finally I modified my launch function to include the check for the active windows
/// <summary>
    /// Starts the new customer.
    /// </summary>
    /// <param name="param">The param.</param>
    public static void StartNewCustomer(Parameter param)
    {
        string windowName = "New Customer";
        if (!IfApplicationWindowOpen(windowName))
        {

            GlobalFactory globalfactory = param.GlobalFactory;

            try
            {
                Generic objNewCustomer = new Generic();
                objNewCustomer.StartNewCustomerFromCustomer(param);
            }
            catch (TypeInitializationException tx)
            {
                globalfactory.ErrorHandler.Log(tx, (int)msmsError.ErrorSeverity.Major | (int)msmsError.ErrorSeverity.User);
            }
            catch (Exception ex)
            {
                globalfactory.ErrorHandler.Log(ex, (int)msmsError.ErrorSeverity.Major | (int)msmsError.ErrorSeverity.User);
            }
        }
        else
        {
            MessageBox.Show("The application " + windowName + " is already open", windowName + ": Launch Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Hope this helps anyone else with the same problem
Regards,
Comic Coder


text:
Q: How to uninstall android apps using the new PackageInstaller api? The old way of uninstalling android apps with ACTION_UNINSTALL_PACKAGE is deprecated in API level 29. Now it's recommended to use PackageInstaller.uninstall(packageName: String, statusReceiver: IntentSender) instead. This is what a came-up with so far:
fun uninstal(){
    val packageName = "some package name"
    val packageInstaller = this.packageManager.packageInstaller
    val intent = Intent(this, this::class.java)
    val sender = PendingIntent.getActivity(this, 0, intent, 0)
    packageInstaller.uninstall(packageName, sender.intentSender)
}

I cannot figure out how to provide the IntentSender. I tried to make an intent from and to the current activity but all this code does is recreate the activity. Any idea please? and thanks

A: The Intent based method still works on API Level 29+ devices. Just change your Intent action to

Intent.ACTION_DELETE

Also you need to add the permission to delete packages as well.

<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES"/>

Here is the complete code :
val pkg             = "package_to_delete"
val uri: Uri        = Uri.fromParts("package", pkg, null)
val uninstallIntent = Intent(Intent.ACTION_DELETE, uri)

startActivityForResult(uninstallIntent, EXIT_REQUEST)

In the above code, pkg is the packageName of the App you want to delete in string format and EXIT_REQUEST is an Integer value.


text:
Q: How to get effects to work one and override others Hi, I have created a picturebox which, when a an effect is selected, it will then change the image in the picture box using the color matrix.
The issues I'm having is if I choose another effect when one is selected the old effect will not disappear, instead it will just stay there and be underneath the new effect selected. The effects I'm using is sepia and greyscale for now, but can anyone help me so that once one effect is selected, the old effect is cleared rather than them just stacking up on one another.
I am using the graphics and colormatrix as well as bitmap and here is the code for my two buttons:
Graphics g;

private void greyscalePicture_Click(object sender, EventArgs e)
{

   Image img = pictureBox.Image;
   Bitmap greyscaleBitmap = new Bitmap(img.Width, img.Height);
   ImageAttributes ia = new ImageAttributes();
   ColorMatrix cmImage = new ColorMatrix(new float[][]
   {
      new float[] {.3f, .3f, .3f, 0, 0},
      new float[] {.59f, .59f, .59f, 0, 0},
      new float[] {.11f, .11f, .11f, 0, 0},
      new float[] {0, 0, 0, 1, 0},
      new float[] {0, 0, 0, 0, 1}
   });
   ia.SetColorMatrix(cmImage);
   g = Graphics.FromImage(greyscaleBitmap);
   g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0,
               img.Width, img.Height, GraphicsUnit.Pixel, ia);
   g.Dispose();
   pictureBox.Image = greyscaleBitmap;
}

// This is the same as the grey effect except
// the float values have been changed
private void sepiaPicture_Click(object sender, EventArgs e)
{
   Image img = pictureBox.Image;
   Bitmap sepiaBitmap = new Bitmap(img.Width, img.Height);
   ImageAttributes ia = new ImageAttributes();
   ColorMatrix cmImage = new ColorMatrix(new float[][]
   {
      new float[] {.393f, .349f, .272f, 0, 0},
      new float[] {.769f, .686f, .534f, 0, 0},
      new float[] {.189f, .168f, .131f, 0, 0},
      new float[] {0, 0, 0, 1, 0},
      new float[] {0, 0, 0, 0, 1}
   });
   ia.SetColorMatrix(cmImage);
   g = Graphics.FromImage(sepiaBitmap);
   g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0,
               img.Width, img.Height, GraphicsUnit.Pixel, ia);
   g.Dispose();
   pictureBox.Image = sepiaBitmap;
}

A: You have to store the original image, apply the effect on this original one not the current one:
//Your form constructor
public Form1(){
   InitializeComponent();
   originalImage = pictureBox.Image;
}
Image originalImage;
private void greyscalePicture_Click(object sender, EventArgs e) {
 Image img = originalImage;// Not pictureBox.Image
 //...
}
private void sepiaPicture_Click(object sender, EventArgs e) {
 Image img = originalImage;// Not pictureBox.Image
 //...
}

The point is whenever you want to save the current state, just update your originalImage to make any next effect apply alternatively.


text:
Q: Pumping water into IndustrialCraft2 machines I'm currently working on a game that I've setup with FTB Beyond. As I'm used to playing with buildcraft installed, I can't seem to find a way of pumping water into various IC2 machines, such as the Ore Washing Plant. I've tried adding a pump from thermal expansion and connected it to the Ore Washing Plant via TE pipes, but with no result. And as far as I can see, there's no native IC2-way of piping in water to the machines.
So my question boils down to: How does one automatically supply IC2 machines with water from a pond a few blocks away? Using any gear available via FTB, that is.

A: Here's a setup I just did using the latest version of the pack in creative mode:

You can see it being powered by a bat box, with water being pumped in using fluid ducts from an Aqueous Accumulator (which is powered by a creative capacitor under it).
As you can see, it's full:

And here we've got it essentially the same way, except using a pressurized fluid conduit from Ender IO:

So the quick-n-cheap route is just use the pump (accumulator) from Thermal Expansion along with the (rather cheap) fluid ducts, if you want to get fancy then you can use other options.
I miss BC too, especially the pump, as it's so versatile. But TE has you covered.

A: IC2 Machines have directional inputs, that allow you to automatically move items through a system. A simple example would be Macerator > Electric Furnace. However, to move the items from one to the other, they need to be pulled out of one specific side from the Macerator, and the pumped into a specific side of the Furnace.
The same is true for the Ore Washing Plant. Basically, with the use of pumps and pipes, you can make sure that your Ore Washing Plant is perpetually filled with water.
This video shows this in more detail.