text:
Q: json combobox mysql Hi guys i m try to make a combobox with json but cant do this righ
Jquery function
$("select#selest").change(function(){
    $("select#reccid").html('<option value="">Carregando...</option>');
    $.getJSON("/inc/geraCidades.php",{estado: $(this).val()}, function(resposta){
        if(resposta === null){
            var options = '<option value="">-</option>';
        }
        else{
            var options = '<option value="">-</option>';
            $.each(resposta, function(key, val) {
                options += '<option value="' + key + '">' + val + '</option>';
            });
        }
        $("select#reccid").html(options);
    })
})

My php file
<?
header("Content-Type: application/json");
include("config.php");
$Estado_Id = mysql_real_escape_string($_REQUEST["estado"]);
$Sql01 = "SELECT * FROM tabcidades WHERE Estado_Id = '$Estado_Id' ORDER BY Cidade_Nome ASC";
$Query01 = mysql_query($Sql01, $Conn);
while($Rs01 = mysql_fetch_array($Query01)){
    //if($Rs01["Cidade_Id"] == $Cidade_Id) $selected = "selected";
    //else $selected = "";
    $array[] = array('key' => $Rs01['Cidade_Id'], 'val' => $Rs01['Cidade_Nome']);
}
 echo json_encode($array);

?>
the return come only object
Thanks for any help

A: Please try below code..
$("select#selest").change(function(){
    $("select#reccid").html('<option value="">Carregando...</option>');
    $.getJSON("/inc/geraCidades.php",{estado: $(this).val()}, function(resposta){
        if(resposta === null){
            var options = '<option value="">-</option>';
        }
        else{
            var options = '<option value="">-</option>';
            $.each(resposta,function(arrayID,resp){
                $.each(resp,function(key,val){
                    options += '<option value="' + key + '">' + val + '</option>';
                });
            });
        }
        $("select#reccid").html(options);
    })
})

That gives me options in second dropdown including key and value like this 1Test
and I have asked for php output i.e. value of $array in php file. Have a look the $array value which prints two dimensional array, so you need to loop two times to set option. Hope this will help you.


text:
Q: Trigger bulkification when adding errors Snippet 1:
trigger AccountValidationTrigger on Account(before update){
    for(Account accObj: Trigger.new){
      if(accObj.Some_Flag__c != TRUE){
        accObj.addError('Some flag should be true');
      }
    }
}

Snippet 2:
trigger AccountValidationTrigger on Account(before update){
    List<Account> errorAcctsList = new List<Account>();
    for(Account accObj: Trigger.new){
      if(accObj.Some_Flag__c != TRUE){
        errorAcctsList.add(accObj);
      }
    }
    for(Account accObj: errorAcctsList){
        accObj.addError('Some flag should be true');
    }
}

Given the above two code snippets, which of the above is a best practice to use in trigger when adding validation logic.
Most of the best practices for trigger bulkification are about reducing number of DML statements but I couldn't find any example on what is the best practice to follow in above situations.

A: The point of bulkification is to perform an operation (such as a SOQL query) so that a set of records are returned together to help performance. This avoids running into governor limits which in turn are (often) a guard against repeating expensive operations. In the query example, returning 101 records in one request is: one request from the app server to the the database, one query plan generation, one query execution and one response from the database back to the app server. Making 101 separate queries would require all those steps to be repeated 101 times.
There is no need to arrange code executed locally in the app server using similar patterns. Generally simple code that is easily understood is best and Premature Optimization is the root of all evil. So the simpler pattern "snippet 1" is the way to go.
(By the way I'm saying "generally" here because in reality there are rarely "best practices" in the sense that a practice is universally "best". There are often several factors at play and what is best in one situation might not be best in another.)
PS
Before introducing design patterns into your code have a think about some of the pros and cons - see e.g. When should I use—and not use—design patterns?

A: Fun fact, if you adopt the latter pattern, you can implement a library like Selector to do the filtering for you.
public with sharing class AccountService
{
    public static Select.Filter isFlagged()
    {
        return Select.Field.isEqual(Account.Some_Flag__c, true);
    }
    public static void validateFlaggedAccounts(List<Account> flaggedAccounts)
    {
        for (Account flaggedAccount : flaggedAccounts)
            flaggedAccount.addError('message');
    }
}

Then in your trigger you can just do:
AccountServices.validateFlaggedAccounts(
    AccountServices.isFlagged().filter(trigger.new, trigger.oldMap)
);

One huge advantage of this pattern is it's way easier to test. You can test the positive/negative filter cases very easily, then test your action completely independently. Separation of concerns, ftw!
static final Integer RECORD_COUNT = Limits.getLimitQueries() + 1;
static testMethod void testIsFlagged_Positive()
{
    List<Account> accounts = new List<Account>();
    for (Integer i = 0; i < RECORD_COUNT; i++)
        accounts.add(new Account(Some_Flag__c=true));

    Test.startTest();
        List<Account> results = AccountService.isFlagged().filter(accounts);
    Test.stopTest();

    system.assertEquals(RECORD_COUNT, results.size(), 'message');
}
static testMethod void testIsFlagged_Negative()
{
    List<Account> accounts = new List<Account>();
    for (Integer i = 0; i < RECORD_COUNT; i++)
        accounts.add(new Account(Some_Flag__c=false));

    Test.startTest();
        List<Account> results = AccountService.isFlagged().filter(accounts);
    Test.stopTest();

    system.assertEquals(0, results.size(), 'message');
}

A: Both will accomplish what you are after, but I tend to prefer Snippet 1 because it simply reduces the number of script statements that need to be evaluated.  In Snippet 2 you are inefficiently iterating twice over the records you want to add the error to (as well as creating more memory overhead by creating another list of records to store temporarily).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Type inference for polymorphic recursive functions The Polymorphic recursion page on Wikipedia gives following example where Haskell's type checker fails to infer type without explicit type annotation:
data Nested a = a :<: (Nested [a]) | Epsilon

length Epsilon    = 0
length (_ :<: xs) = 1 + length xs

When compiling this code, GHC says:
Occurs check: cannot construct the infinite type: t ~ [t]
Expected type: Nested t
  Actual type: Nested [t]
Relevant bindings include
  xs :: Nested [t]
  length :: Nested t -> a

I understand how t becomes [t], but I don't see why it is a problem for a typechecker. If we let length be Nested t -> a and then stumbled upon length xs and let it be Nested [t] -> b, why can't we assume that a ~ b and successfully typecheck this? Or the problem is somewhere else?


text:
Q: C# EndsWith more than one value How can i get more values in a EndsWith?
For example
if(textbox1.Text.EndsWith("hotmail.com" && "anothermail.com"){

}

What to do?

A: You can create an extension method:
public static bool EndsWithAny(this string str, params string[] search)
{
    return search.Any(s => str.EndsWith(s));
}

//Call
bool found = str.EndsWithAny("hotmail.com", "anothermail.com");

A: If you want to get the results where the value ends with one string, or ends with the other string, then combine the two checks with a logical or:
if(textbox1.Text.EndsWith("hotmail.com") || textbox1.Text.EndsWith("anothermail.com")) { ... }

A: string[] ends = new string[] { "hotmail.com" , "anothermail.com" };
string text = "example.hotmail.com2";
bool endsWith = ends.Any(e => text.EndsWith(e));

A: You could use a collection and Any+EndsWith:
var mails = new[] { "hotmail.com", "anothermail.com" };
bool endsWithAny= mails.Any(textbox1.Text.EndsWith);


text:
Q: webpack.config with font-awesome I am going to use fontawesome 5 in my source code, but I have some trouble here.
I've installed 4 npm modules.

"@fortawesome/fontawesome-free": "^5.11.2",
"@fortawesome/fontawesome-svg-core": "^1.2.25",
"@fortawesome/free-solid-svg-icons": "^5.11.2",
"@fortawesome/react-fontawesome": "^0.1.7",

webpack.config.js
'use strict';

/**
 * Webpack Config
 */
const path = require('path');
const fs = require('fs');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';

// Make sure any symlinks in the project folder are resolved:
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

// plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const CopyWebpackPlugin = require('copy-webpack-plugin');

// the path(s) that should be cleaned
let pathsToClean = [
    'dist',
    'build'
]

// the clean options to use
let cleanOptions = {
    root: __dirname,
    verbose: false, // Write logs to console.
    dry: false
}

module.exports = {
    entry: ["babel-polyfill", "react-hot-loader/patch", "./src/index.js"],
    output: {
        // The build folder.
        path: resolveApp('build'),
        // Generated JS file names (with nested folders).
        // There will be one main bundle, and one file per asynchronous chunk.
        // We don't currently advertise code splitting but Webpack supports it.
        filename: 'assets/js/[name].[hash:8].js',
        chunkFilename: 'assets/js/[name].[hash:8].chunk.js',
        // We inferred the "public path" (such as / or /my-project) from homepage.
        publicPath: publicPath,
        hotUpdateChunkFilename: 'hot/hot-update.js',
        hotUpdateMainFilename: 'hot/hot-update.json'
    },
    devServer: {
        contentBase: './src/index.js',
        compress: true,
        port: 3000, // port number
        historyApiFallback: true,
        quiet: true
    },
    // resolve alias (Absolute paths)
    resolve: {
        alias: {
            Components: path.resolve(__dirname, 'src/components/'),
            Containers: path.resolve(__dirname, 'src/containers/'),
            Assets: path.resolve(__dirname, 'src/assets/'),
            Util: path.resolve(__dirname, 'src/util/'),
            Routes: path.resolve(__dirname, 'src/routes/'),
            Constants: path.resolve(__dirname, 'src/constants/'),
            Redux: path.resolve(__dirname, 'src/redux/'),
            Data: path.resolve(__dirname, 'src/data/')
        }
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, "css-loader"]
            },
            // Scss compiler
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "sass-loader"
                ]
            }
        ]
    },
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                uglifyOptions: {
                    compress: false,
                    ecma: 6,
                    mangle: true
                },
                sourceMap: true
            }),
            new OptimizeCSSAssetsPlugin({})
        ]
    },
    performance: {
        hints: process.env.NODE_ENV === 'production' ? "warning" : false
    },
    plugins: [
        new CopyWebpackPlugin([
            { from: 'src/assets/img', to: 'assets/img' }, { from: 'src/assets/fonts', to: 'assets/fonts' }
        ]),
        new FriendlyErrorsWebpackPlugin(),
        new CleanWebpackPlugin(pathsToClean, cleanOptions),
        new HtmlWebPackPlugin({
            template: "./public/index.html",
            filename: "./index.html",
            favicon: './public/favicon.ico'
        }),
        new MiniCssExtractPlugin({
            filename: "assets/css/[name].[hash:8].css"
        }),
        new MiniCssExtractPlugin({
            filename: "[name].[hash:8].css",
            chunkFilename: "[id].[hash:8].css"
        })
    ]
};

And I've got below error when I wrote import '@fortawesome/fontawesome-free/css/solid.css';
Failed to compile with 1 errors                                                                                3:21:04 AM
 error  in ./node_modules/@fortawesome/fontawesome-free/css/solid.css

Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleParseError: Module parse failed: Unexpected character ' ' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
    at handleParseError (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:469:19)
    at doBuild.err (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:503:5)
    at runLoaders (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:358:12)
    at E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
    at Array.<anonymous> (E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)    at provider (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9)
    at E:\workspace\pulse\projectai-pulse-survey\node_modules\graceful-fs\graceful-fs.js:115:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)

 @ ./src/components/MyMap/KGraph/index.js 17:0-54
 @ ./src/components/MyMap/index.js
 @ ./src/routes/mymap/index.js
 @ ./src/routes/index.js
 @ ./src/containers/App.js
 @ ./src/App.js
 @ ./src/index.js
 @ multi babel-polyfill react-hot-loader/patch ./src/index.js

I've tried to many ways to solve this, but all are failed.
Please help me.

A: In my case in file-loader or url-loader instead of testing for only image file extentions, I've also added font extentions like this:
module: {
  rules: [
   {
    test: /\.(png|svg|jpg|jpeg|gif|woff|woff2|eot|ttf|)$/i,
    use: [
      {
        loader: "file-loader",
        options: {//your options},
      }
      // ...other loaders here
    ],
  },
  ]
}

A: Try to change the import of the 'CSS' file to import ''~@fortawesome/fontawesome-free/css/solid.css'', as suggested here.

A: Solved!
I've added the below codes to webpack.config.js
module: {
    rules: [
        ...
        {
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            loader: 'url-loader?limit=100000'
        }
    ]
}

Thanks


text:
Q: Dynamic array of strings I have to dynamically allocate array of words. Words are stored in a file separated by variable count of white-space characters. I don't know how many words is in the file a they can have variable length.
I have this code:
void readWord(FILE* stream, char *word, char first_c) {

    word[0] = first_c;
    char val;
    int wlen = 1;
    // isWhitespac is my function - tests if char is blank or '\n'
    while ((val = fgetc(stream)) != EOF && isWhitespace(val) == 0) {
        wlen++;
        word = realloc(word, (wlen+1) * sizeof (char));

        word[wlen-1] = val;

    }
    word[wlen] = '\0';
}

int readList(const char *file) {

    FILE* f;
    char **arr;
    char val;
    int wcount = 0;

    arr = malloc(sizeof (char*));
    f = fopen(file, "r");

    while (fscanf(f, " %c", &val) == 1) {
        wcount++;
        arr = realloc(arr, wcount * sizeof (char *));

        arr[wcount - 1] = malloc(sizeof (char));

        readWord(f, arr[wcount-1], val);
        printf("%s\n", arr[wcount-1]);

    }

    for (int i = 0; i < wcount; ++i) {
        free(arr[i]);
    }

    free(arr);

    fclose(f);
    return 0;
}

It appears to work fine, it reads a prints all the words. But when I run the program with Valgrind the are too many errors, which I can't find. Could anyone help me? (I know I have to test if malloc and others went fine, it is just a test func.)
The Valgrind log is quite long, should I post it too?

A: One of the issues is that you do realloc inside readWord. If realloc allocates a new buffer and doesn't just extend the current one then your code will crash (you will double free the pointer) and this is what Valgrind picks up. To fix this I would rewrite the code so it returns a pointer instead of void.
char * readWord(FILE* stream, char *word, char first_c) {
    word[0] = first_c;
    char val;
    int wlen = 1;
    // isWhitespac is my function - tests if char is blank or '\n'
    while ((val = fgetc(stream)) != EOF && isWhitespace(val) == 0) {
      wlen++;
      word = realloc(word, (wlen+1) * sizeof (char));
      word[wlen-1] = val;
    }
    word[wlen] = '\0';
    return word;
}

And then change the loop in readList to this:
while (fscanf(f, " %c", &val) == 1) {
  wcount++;
  arr = realloc(arr, wcount * sizeof (char *));
  arr[wcount-1]=malloc(sizeof(char));
  arr[wcount - 1] = readWord(f, arr[wcount-1],  val);
  printf("%s\n", arr[wcount-1]);
}


text:
Q: Access 2007 Report Grouping I'm using an access 2007 database to track and report down time and reliability of devices. I've got four different devices in the Devices table. I also track all downtime occurrences in it's own table. We also need to know when the devices are actually in use, so we can tell if the downtime affected our operation at all. We keep track of use in a different table.
My report looks up all the downtime occurrences, groups them via device and then uses the group footer to sub total the downtime, look up use for the period and calculate the up time percentage.
My problem is that if there is no downtime, the access report skips that entire device (obviously because it doesn't know about it from just querying the downtime table). I would like to always see the grouping for all devices and if there is no downtime it should still show the footer with total use and reliability statistics.
I realize access isn't maybe the best tool, but in my work environment that's all I have easy access too.  I also realize without getting overly specific it might be hard to give concrete answers but hopefully someone can steer me in the right direction.
Thanks for any insight.

A: You do not provide details, so here is a somewhat vague answer. The best way to do this is usually to set up your query for the report so that it always contains a full list of devices. This can be achieved by a LEFT JOIN from the main device table to the data table. You can use Nz to return a suitable value if nulls are a problem.
SELECT A.DeviceID, A.Device, A.Col1, B.Col2, B.Col3
FROM TableWithFullListOfDevices A
LEFT JOIN TableWithDownTimeResults B


text:
Q: For loop wait for all CompletableFutures to give result, and add result to int I have a method getCount(id) that returns an integer from a database, as a CompletableFuture. I want to loop through all the ids, and get the result for all of them, and add them to one global int. Then I want to do something with that int:
int totalCount;
for (String id : API.getIDs()) {
    //OtherAPI.getCount(id) will return the CompletableFuture<Integer>
    OtherAPI.getCount(id).thenAccept(count -> totalCount += count);
}

System.out.println("" + totalCount);

This gives an error, because you can't add an integer to another integer in thenAccept, because it's a consumer. What is the way to do this?

A: Mind that the function passed to thenAccept can be performed by an arbitrary thread, so thankfully, Java does not allow them to modify a local variable. When you change the variable to a field on the heap, the compiler would accept it, but the result would be entirely broken.
The simplest solution would be
int totalCount = 0;
for(String id: API.getIDs()) {
    totalCount += OtherAPI.getCount(id).join();
}

It just waits for the availability of each value, to sum them locally. Depending on the operations encapsulated by the OtherAPI.getCount(…) calls, this might even be the most efficient solution.
But when these operations take a significant time and can truly run in parallel, i.e. do not depend on a shared resource internally, it might be beneficial not to wait before all operations have been commenced.
You can do this like
CompletableFuture<Integer> result = CompletableFuture.completedFuture(0);
for(String id: API.getIDs()) {
    result = result.thenCombine(OtherAPI.getCount(id), Integer::sum);
}
System.out.println(result.join());

Here, the loop is entirely wait-free. It will schedule the summing operation, to be done when two operations have been completed. Then, only the join call at the end will wait for the final result. At this point, all asynchronous operations have been submitted already.


text:
Q: about contextmenustrip I've added contextmenustrip control at the time of designing of my application. And i want to edit that contxt menu at run time. And i want to add another menu & submenu on that context menu. And i want to add handler function for that runtime created menus.
Whether is it possible? If possible then provide some documentation.
thanks.

A: I got an answer of my issue.
the sample code used for solving this issue is as follows-
ToolStripMenuItem addContactToGroup = new ToolStripMenuItem();
addContactToGroup.Name = "addContactToGroupToolStripMenuItem";
addContactToGroup.Text = "Add Contact To Group";
addContactToGroup.Click += new System.EventHandler(addContactToGroup_Click);
this.contextMenuStripXtraGrid.Items.AddRange(new ToolStripItem[] { addContactToGroup });
gridControl1.ContextMenuStrip = this.contextMenuStripXtraGrid;

here this means form where contextmenustrip control is inserted.


text:
Q: SC delete  does not work I am running the sc delete command from C# code. But it always returns,

[SC] OpenService FAILED 1060: "The specified service does not exist as an installed service"

I tried executing the code a number of times but I still get the same error. But If I go to the command prompt and execute the command, the service will be deleted successfully.
And yes, if I execute the command again on command prompt it gives me the same above error. So I want to know, why it does not delete from C# code, am I missing something?
var procStartInfo = new ProcessStartInfo("cmd.exe", "/c sc delete 'myService'")
{
  RedirectStandardOutput = true,
  UseShellExecute = false,
  CreateNoWindow = false
};

var proc = new Process { StartInfo = procStartInfo };
proc.Start();

// Get the output into a string
var result = proc.StandardOutput.ReadToEnd();

A: Its the single quotes. They don't work.
var procStartInfo = new ProcessStartInfo("cmd.exe", "/c sc delete myService")

to handle the double quotes for a spaced service name then you need to escape them.
var procStartInfo = new ProcessStartInfo("cmd.exe", "/c sc delete \"my Service\"")


text:
Q: Try - catch SQL I cant force my error sad face to come up on this code. Can someone help please I just get a normal error message not the one in the catch. I just take out a bit of code to force an error is this right
declare @Color Table
(color char(12))

insert @Color
Values('white'),
('Red'),
('black'),
('yellow');

Declare @make Table
(make char(12))

insert @make
Values('Polo'),
('Golf'),
('A1'),
('Metro');

Begin try
Select *
  From @Color Cross Join @make ;
End Try
Begin Catch
   PRINT ';('
end catch
  Print 'Done'

A: I ran your excerpt in SQL Server 2012, and it did not produce an error at all. I got a result set of 16 rows.
Here is some code that will catch an error and tell you what went wrong:
DECLARE @Color TABLE
(color char(12));

INSERT @Color
VALUES('white'),
('Red'),
('black'),
('yellow');

BEGIN TRY;
    SELECT CAST(color AS int)
        FROM @Color;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

The output is:


text:
Q: How to calculate the median age of a population? I want to calculate the median age of a population. Consider the following example data (downloaded from Statistics Canada's CANSIM database, Table 051-0001):
Table 051-0001 Estimates of population, by age group and sex for July 1, Canada, provinces and territories, annual (persons unless otherwise noted)
Survey or program details:
Estimates of Population by Age and Sex for Canada, Provinces and Territories - 3604
Geography      Age      2010      2011      2012      2013      2014
Canada           0    377861    376321    376593    381689    384566
Canada           1    380538    379990    379191    379400    384085
Canada           2    380634    383179    383355    382164    382320
Canada           3    371478    383741    386305    386406    384721
Canada           4    362882    375833    387091    389512    389258
Canada           5    356590    366757    379364    390614    392709
Canada           6    360976    361038    370316    382704    393919
Canada           7    355169    363440    364337    373378    385791
Canada           8    357366    358621    366509    367203    375972
Canada           9    361252    360577    361705    369300    369853
Canada          10    374141    365198    363513    364429    371892
Canada          11    376153    376458    368165    366089    366754
Canada          12    386812    379838    379378    370725    368303
Canada          13    400765    391245    382591    381913    373366
Canada          14    421855    405425    394646    385845    385158
Canada          15    434175    426802    409598    398813    390141
Canada          16    438635    440145    432615    415325    404911
Canada          17    446950    446524    446819    438832    422155
Canada          18    457629    455872    456107    456347    449780
Canada          19    472134    469609    469648    469727    471713
Canada          20    479938    479650    480075    478935    479825
Canada          21    465581    484077    487441    487222    487303
Canada          22    451825    470052    492089    494807    494773
Canada          23    457019    458775    478405    500371    502743
Canada          24    468109    461800    466140    485206    507465
Canada          25    472877    471522    468571    472175    491796
Canada          26    471323    475052    478176    474765    478485
Canada          27    470566    474287    481927    484782    481007
Canada          28    468454    475287    481774    488559    491073
Canada          29    474732    473693    482673    488843    495415
Canada          30    468396    479377    481415    489943    495625
Canada          31    457343    472955    486914    488681    496949
Canada          32    450990    462922    480345    493717    495002
Canada          33    452786    455951    469502    486633    499657
Canada          34    454337    456750    462188    475678    492631
Canada          35    456131    457914    462422    467980    481122
Canada          36    444761    458413    463276    467283    472694
Canada          37    447653    448563    463120    467676    471389
Canada          38    454974    450150    452853    467353    471303
Canada          39    479412    458047    454151    456406    470625
Canada          40    476941    480129    461608    457435    459218
Canada          41    473754    478010    483497    464567    459997
Canada          42    470960    475541    480964    486012    466836
Canada          43    476994    473014    478112    483096    487941
Canada          44    505091    479224    475161    480000    484701
Canada          45    543975    506180    480754    476662    481251
Canada          46    560528    541424    507546    481692    477527
Canada          47    565680    557834    542469    508247    482163
Canada          48    550871    562501    558604    542971    508357
Canada          49    559845    551970    563107    558829    542849
Canada          50    549137    558958    551916    563085    558602
Canada          51    535778    548847    558693    551419    562609
Canada          52    530407    536639    548423    557898    550499
Canada          53    518528    529913    535794    547485    556782
Canada          54    501147    516903    528855    534558    546135
Canada          55    496890    501158    515688    527602    532979
Canada          56    476058    493948    499663    514369    525968
Canada          57    452959    473623    492514    498260    512603
Canada          58    434140    451080    471946    491181    496564
Canada          59    426554    433281    449217    470450    489202
Canada          60    416427    424456    431432    447732    468404
Canada          61    406686    414501    422373    429874    445569
Canada          62    406030    405624    412256    420656    427664
Canada          63    409513    404282    403263    410629    418399
Canada          64    343036    401580    401573    401279    408094
Canada          65    319975    344130    398603    399294    398380
Canada          66    310757    317981    341249    395875    396003
Canada          67    297341    306903    314982    338733    392348
Canada          68    274022    292908    303625    312358    335276
Canada          69    262547    271018    289468    300739    308870
Canada          70    243273    257990    267625    286330    297083
Canada          71    233870    240638    254195    264252    282308
Canada          72    222439    230156    236842    250713    260198
Canada          73    209795    218638    226001    233119    246393
Canada          74    205522    206400    214332    222005    228699
Canada          75    196095    200626    201812    209949    217227
Canada          76    185698    190737    195686    197222    204987
Canada          77    183420    180672    185358    190437    191834
Canada          78    177259    176879    174946    179710    184600
Canada          79    170901    170424    170616    168901    173534
Canada          80    159809    163436    163608    163924    162272
Canada          81    146075    152274    156213    156439    156796
Canada          82    137515    138753    144686    148468    148791
Canada          83    125378    129386    131081    136719    140405
Canada          84    116263    117291    121359    122961    128353
Canada          85    105468    107226    109197    112966    114566
Canada          86     94205     96193     99099    100911    104508
Canada          87     82396     85051     88042     90690     92440
Canada          88     73145     73870     77032     79728     82232
Canada          89     62417     64399     66201     69033     71573
Canada         90+    200558    216331    233539    249385    265581
Canada   MedianAge      39.8        40      40.1      40.2      40.4
Source:
Statistics Canada. Table 051-0001 - Estimates of population, by age group and sex for July 1, Canada, provinces and territories, annual (persons unless otherwise noted)
(accessed: February 24, 2015)

In order to establish the median for (say) 2010, we calculate the cumulative totals:
Geography      Age      2010  Cumulative
Canada           0    377861      377861
Canada           1    380538      758399
Canada           2    380634     1139033
Canada           3    371478     1510511
Canada           4    362882     1873393
Canada           5    356590     2229983
Canada           6    360976     2590959
Canada           7    355169     2946128
Canada           8    357366     3303494
Canada           9    361252     3664746
Canada          10    374141     4038887
Canada          11    376153     4415040
Canada          12    386812     4801852
Canada          13    400765     5202617
Canada          14    421855     5624472
Canada          15    434175     6058647
Canada          16    438635     6497282
Canada          17    446950     6944232
Canada          18    457629     7401861
Canada          19    472134     7873995
Canada          20    479938     8353933
Canada          21    465581     8819514
Canada          22    451825     9271339
Canada          23    457019     9728358
Canada          24    468109    10196467
Canada          25    472877    10669344
Canada          26    471323    11140667
Canada          27    470566    11611233
Canada          28    468454    12079687
Canada          29    474732    12554419
Canada          30    468396    13022815
Canada          31    457343    13480158
Canada          32    450990    13931148
Canada          33    452786    14383934
Canada          34    454337    14838271
Canada          35    456131    15294402
Canada          36    444761    15739163
Canada          37    447653    16186816
Canada          38    454974    16641790
Canada          39    479412    17121202
Canada          40    476941    17598143
Canada          41    473754    18071897
Canada          42    470960    18542857
Canada          43    476994    19019851
Canada          44    505091    19524942
Canada          45    543975    20068917
Canada          46    560528    20629445
Canada          47    565680    21195125
Canada          48    550871    21745996
Canada          49    559845    22305841
Canada          50    549137    22854978
Canada          51    535778    23390756
Canada          52    530407    23921163
Canada          53    518528    24439691
Canada          54    501147    24940838
Canada          55    496890    25437728
Canada          56    476058    25913786
Canada          57    452959    26366745
Canada          58    434140    26800885
Canada          59    426554    27227439
Canada          60    416427    27643866
Canada          61    406686    28050552
Canada          62    406030    28456582
Canada          63    409513    28866095
Canada          64    343036    29209131
Canada          65    319975    29529106
Canada          66    310757    29839863
Canada          67    297341    30137204
Canada          68    274022    30411226
Canada          69    262547    30673773
Canada          70    243273    30917046
Canada          71    233870    31150916
Canada          72    222439    31373355
Canada          73    209795    31583150
Canada          74    205522    31788672
Canada          75    196095    31984767
Canada          76    185698    32170465
Canada          77    183420    32353885
Canada          78    177259    32531144
Canada          79    170901    32702045
Canada          80    159809    32861854
Canada          81    146075    33007929
Canada          82    137515    33145444
Canada          83    125378    33270822
Canada          84    116263    33387085
Canada          85    105468    33492553
Canada          86     94205    33586758
Canada          87     82396    33669154
Canada          88     73145    33742299
Canada          89     62417    33804716
Canada         90+    200558    34005274   <--- Total population

The total population contains $34\,005\,274$ individuals, with the "middle (or median) person" being person number $34\,005\,274 \div 2 = 17\,002\,637 = M$. A lookup shows that this person is said to be between 38 and 39 years old since
$$
  \text{Cumulative}(38) = \overbrace{16\,641\,790}^{C(38)}
                        < \overbrace{17\,002\,637}^{M}
                        < \overbrace{17\,121\,202}^{C(39)}
                        = \text{Cumulative}(39).
$$
To estimate the proportion between 38 and 39, we assume that the population is evenly distributed between the age cohorts based on the cohort size. As such, this "median person" has age
$$
  38 +
  \frac{\overbrace{17\,002\,637}^M - \overbrace{16\,641\,790}^{C(38)}}
    {\underbrace{17\,121\,202}_{C(39)} - \underbrace{16\,641\,790}_{C(38)}}
  = 38 + \frac{360\,847}{479\,412}
  \approx 38.8
  = \bar{M}.
$$
In the above calculation, the "median cohort portion" is calculated to estimate the age above the cohort division.
To me this approach seems intuitive and sound. However, Statistics Canada reports the median age as
$$
  39.8 = \bar{M} + 1.
$$
Why is that?
I assume this has to do with the fact that the population cohort aged 20 (say) is in their 21st year of life? Even if this is the case, a median age of 39.8 points to someone that is older than 39*, yet the "median person" is somewhere between 38 and 39 years old; i.e., younger than 39. Unless, of course, that proposition is incorrect.

A: The trick here is understanding the grouping categories of age here.  The age group "39" is people aged 39 to less than 40 (i.e. 39 - 39.99999999).  So if you look at the cumulative total for the 38 year old group, you will see the value is 16,641,790 as you've correctly noted.  The cumulative total for the 39 year old group, which is really the "39 to < 40 year old group) is 17,121,202.  There are a total of 479,412 individuals who are older than 39 and less than 40.  We know from your table that there are 16,641,790 individuals who are less than 39 years old.  So starting at person 16,641,791 and going through person 17,121,202 we find our 39 to less than 40 year olds.  There are 479,412 people in this group.  By your faulty assumption of equal distribution of ages, if we take $479,412\over10$, we can construct the following table, roughly, by adding this amount to the end of the cumulative figure of the 38th age group in an iterative fashion:
Age     Begin       End
39.0    16,641,791  16,689,731
39.1    16,689,732  16,737,672
39.2    16,737,673  16,785,614
39.3    16,785,615  16,833,555
39.4    16,833,556  16,881,496
39.5    16,881,497  16,929,437
39.6    16,929,438  16,977,378
39.7    16,977,379  17,025,320
39.8    17,025,321  17,073,261
39.9    17,073,262  17,121,202

According to these calculations, the median would fall somewhere around 39.7.  Of course, birthday months and ages are not uniformly distributed, so this accounts for the 0.2 discrepancy we see between this "on the back of a napkin" calculation and the official statistic.
I hope this helps.


text:
Q: svg rotation, scale and translate with mouse Trying to apply rotation, move and resize using mouse on SVG element. Here you can test this.
Currently I worked on South control, Center control and Rotate control.

*

*Rotation works perfectly fine, I can rotate, stop and again rotate. But after I move the element by dragging center point, the rotation flickers first time and rotation starting point is different. I belive this is because center position is changed after translate. I tried recalculating center position but it did not work.

*And scaling is moving the element instead of increasing the size.
Please help me on this. I am missing some adjustments here.
Note: First you have draw some path with mouse to get controls on it.

var svg = document.querySelector('.container');
var svgns = 'http://www.w3.org/2000/svg';

var path = document.createElementNS(svgns, 'path');
svg.appendChild(path);

var points = [];
var Resizer_Instance = null;

var boundingBox = svg.getBoundingClientRect();

var toSVGPath = function(points) {
  var SVGPath = '';
  for (var i = 0; i < points.length; i++) {
    var prefix = (i == 0) ? 'M' : 'L';
    SVGPath += prefix + points[i].x + ' ' + points[i].y + ' ';
  }
  return SVGPath;
};

var create_mousedown = false;

var createStart = function(event) {
  create_mousedown = true;
};

var creating = function(event) {
  if (create_mousedown) {
    var point = svg.createSVGPoint();
    point.x = event.clientX - boundingBox.left;
    point.y = event.clientY - boundingBox.top;
    var t = point.matrixTransform(svg.getScreenCTM().inverse());
    points.push(t);
    path.setAttributeNS(null, 'd', toSVGPath(points));
  }
};

var createEnd = function(event) {
  create_mousedown = true;
  svg.removeEventListener('mousedown', createStart);
  svg.removeEventListener('mousemove', creating);
  svg.removeEventListener('mouseup', createEnd);
  setTimeout(function functionName() {
    Resizer_Instance = new Resizer(path, svg);
  }, 500);
};

svg.addEventListener('mousedown', createStart);
svg.addEventListener('mousemove', creating);
svg.addEventListener('mouseup', createEnd);

var Resizer = (function() {

  function Resizer(element) {
    var that = this;
    that.element = element;
    createSelector.call(that);

    document.addEventListener('mousemove', dragging);
    document.addEventListener('mouseup', dragend);

  }

  var RAD2DEG = 180 / Math.PI;

  function angleBetweenPoints(p1, p2) {
    var angle = null;
    if (p1.x == p2.x && p1.y == p2.y)
      angle = Math.PI / 2;
    else
      angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
    return (angle * RAD2DEG) + -90;
  }

  function controlPositions(el) {
    var pt = svg.createSVGPoint();
    var bbox = el.getBoundingClientRect();
    var matrix = el.getScreenCTM().inverse();
    var halfWidth = bbox.width / 2;
    var halfHeight = bbox.height / 2;
    var placements = {};

    pt.x = bbox.left;
    pt.y = bbox.top;

    placements['nw'] = pt.matrixTransform(matrix);
    pt.x += halfWidth;
    placements['n'] = pt.matrixTransform(matrix);
    pt.x += halfWidth;
    placements['ne'] = pt.matrixTransform(matrix);
    pt.y += halfHeight;
    placements['e'] = pt.matrixTransform(matrix);
    pt.y += halfHeight;
    placements['se'] = pt.matrixTransform(svg.getScreenCTM().inverse());
    pt.x -= halfWidth;
    placements['s'] = pt.matrixTransform(matrix);
    pt.x -= halfWidth;
    placements['sw'] = pt.matrixTransform(matrix);
    pt.y -= halfHeight;
    placements['w'] = pt.matrixTransform(matrix);
    pt.x += halfWidth;
    placements['center'] = pt.matrixTransform(matrix);
    pt.y -= (halfHeight + 30);
    placements['rot'] = pt.matrixTransform(matrix);

    return placements;
  }

  var dragging_element = null;

  var dragstart = function(event) {
    var box = this;
    var context = box.context;
    var rootContext = context.rootContext;
    rootContext.current_handle_inaction = context.direction;
    dragging_element = box;
  };

  var dragging = function(event) {
    if (!dragging_element) return;
    var box = dragging_element;
    var context = box.context;
    var rootContext = context.rootContext;
    var currentHandle = rootContext.current_handle_inaction;
    var control_points = rootContext.control_points;

    if (currentHandle === context.direction) {
      var point = svg.createSVGPoint();
      point.x = event.clientX;
      point.y = event.clientY;
      var element = rootContext.element;
      var transformed = point.matrixTransform(svg.getScreenCTM().inverse());

      var centerPosition = context.center;

      rootContext.angle = rootContext.angle || 0;
      rootContext.hMove = rootContext.hMove || 0;
      rootContext.vMove = rootContext.vMove || 0;
      rootContext.scaleX = rootContext.scaleX || 1;
      rootContext.scaleY = rootContext.scaleY || 1;

      switch (currentHandle) {
        case "rot":
          rootContext.angle = angleBetweenPoints(transformed, centerPosition);
          break;
        case "center":
          rootContext.hMove = transformed.x - centerPosition.x;
          rootContext.vMove = transformed.y - centerPosition.y;
          break;
        case "s":
          var startPos = control_points[currentHandle];
          var vMove = transformed.y - startPos.y;
          rootContext.scaleY += (vMove > 0 ? -1 : 1) * 0.001;
          break;
      }

      var move_transform = "translate(" + rootContext.hMove + " " + rootContext.vMove + ")";
      var rotate_transform = "rotate(" + rootContext.angle + ", " + centerPosition.x + ", " + centerPosition.y + ")";
      var scale_transform = "scale(" + rootContext.scaleX + ", " + rootContext.scaleY + ")";

      var transform = [move_transform, rotate_transform, scale_transform].join(' ');

      rootContext.element.setAttribute('transform', transform);
      rootContext.controlGroup.setAttribute('transform', transform);
    }
  };

  var dragend = function() {
    if (!dragging_element) return;
    var box = dragging_element;
    var context = box.context;
    var rootContext = context.rootContext;
    delete rootContext.current_handle_inaction;
    // createSelector.call(rootContext);
    dragging_element = null;
  };

  var adjustPositions = function() {
    var that = this;
    var control_points = that.control_points;
    var controlGroup = that.controlGroup;
    var point = svg.createSVGPoint();
    for (var direction in control_points) {
      var dP = control_points[direction];
      point.x = dP.x;
      point.y = dP.y;
      debugger;
      control_points[direction] = point.matrixTransform(controlGroup.getScreenCTM().inverse());
    }
    return control_points;
  };

  var Deg2Rad = 0.017453292519943295;

  var createSelector = function() {
    var that = this;
    var points = that.control_points;
    if (points) {
      points = adjustPositions.call(that);
    } else {
      points = controlPositions(that.element, svg);
    }
    that.control_points = points;
    var existingBoxes = {};
    var controlGroup = that.controlGroup;

    if (!controlGroup) {
      controlGroup = document.createElementNS(svgns, 'g');
      that.controlGroup = controlGroup;
      svg.appendChild(controlGroup);
    }

    that.control_boxes = that.control_boxes || {};

    var line_name = "connecting-line",
      line_element = that.control_boxes['connecting-line'];

    var line_route = ["nw", "n", "rot", 'n', "ne", "e", "se", "s", "sw", "w", "nw"];

    if (!line_element) {
      line_element = document.createElementNS(svgns, 'path');
      line_element.style.cssText = "fill: none; stroke: #f41542; opacity: 0.5";

      that.control_boxes[line_name] = line_element;
      controlGroup.appendChild(line_element);

      var pathString = "";

      line_route.forEach(function(direction) {
        var point = points[direction];
        var command = pathString.length === 0 ? "M" : " L ";
        pathString += (command + point.x + " " + point.y);
      });

      line_element.setAttribute('d', pathString);
    }

    Object.keys(points).forEach(function(direction) {
      var point = points[direction];
      var box = that.control_boxes[direction];
      if (!box) {
        box = document.createElementNS(svgns, 'circle');
        box.style.cssText = "fill: #5AABAB";

        that.control_boxes[direction] = box;
        box.setAttributeNS(null, 'r', 3);
        box.setAttribute('handle', direction);

        box.addEventListener('mousedown', dragstart.bind(box));

        controlGroup.appendChild(box);
      }

      box.setAttributeNS(null, 'cx', point.x);
      box.setAttributeNS(null, 'cy', point.y);

      box.context = {
        point: point,
        direction: direction,
        rootContext: that,
        center: points.center
      };

    });

  };

  var prototype = {
    constructor: Resizer
  };
  Resizer.prototype = prototype;
  return Resizer;
})();
path {
  fill: none;
  stroke: #42B6DF;
}
body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
}
<svg class="container" version="1.1" baseProfile="full" style="position:absolute;left:0;top:0;height:100%;width:100%;-ms-transform:scale(1,1);transform:scale(1,1);-webkit-transform:scale(1,1);-moz-transform:scale(1,1);-o-transform:scale(1,1);transform:scale(1,1);-ms-transform-origin:0, 0;-webkit-transform-origin:0, 0;-moz-transform-origin:0, 0;-o-transform-origin:0, 0;transform-origin:0, 0"
viewBox="-220.38356461849224 6442.3347962008365 454.7376658611161 114.54981723871151"></svg>

A: You can't easily handle all three transform operations (translate, scale and rotate) with just those three transform functions alone.  You actually should use four functions.
You should remember the original centre point of the element. Let's call this ocx and ocy.  Then do the following:

*

*translate the original centre point to the origin

*perform the scale

*perform the rotation

*translate the centre back to the new (current) centre position.

So the transform string would look something like this:
transform="translate(ncx,ncy) rotate(rot) scale(sx,sy) translate(-ocx,-ocy)"

This way you can keep all the operations isolated, and you don't need to alter the others when one changes.

A: You are currently calculating angle in relation to the initial center of the figure (the one when you have just drawn it). This is wrong - you need to calculate angle in relation to the center of the figure after previous move.
Fiddle
I've stripped the parts that I didn't change.
var dragging = function(event) {
    ...

    if (currentHandle === context.direction) {
        ...

        var initialCenterPosition = context.center,
            // use the coordinates saved after last move or
            // initial coordinates if there are none saved
            previousCenterPosition = rootContext.previousCenterPosition || initialCenterPosition;

        ...

        switch (currentHandle) {
            case "rot":
                rootContext.angle = angleBetweenPoints(transformed, previousCenterPosition);
                break;
            case "center":
                rootContext.hMove = transformed.x - initialCenterPosition.x;
                rootContext.vMove = transformed.y - initialCenterPosition.y;

                // remember the new center coordinates
                rootContext.previousCenterPosition = {
                    x: transformed.x,
                    y: transformed.y
                };
                break;
            case "s":
                ...
        }

        var move_transform = "translate(" + rootContext.hMove + " " + rootContext.vMove + ")";
        var rotate_transform = "rotate(" + rootContext.angle + ", " + initialCenterPosition.x + ", " + initialCenterPosition.y + ")";
        var scale_transform = "scale(" + rootContext.scaleX + ", " + rootContext.scaleY + ")";

        ...
    }
}


text:
Q: How to wrap the first three tags with div? I am getting some dynamic code and I have to wrap the first three element with div. I tried the below code but it's not working.

    <form class="cart">
        <button></button>

        <button></button>
        <button></button>
    </form>

$(function(){
    $('.cart').wrap('

');
});

So my expectation output is,

    <form class="cart">

            <button></button>

            <button></button>

        <button></button>
    </form>

A: A note on Tibebes. M's answer: as of jQuery 3.4, the selector :lt() is deprecated. You can use .slice() as well.
Source

$(function ()
{
    $('.cart>*').slice(0, 3).wrapAll('

');
});
.summary {
  background-color: red;
}

.product-tab {
  background-color: blue;
}

      <form class="cart">
        <button></button>

        <button></button>
        <button></button>
      </form>

A: Here is one approach:
using .cart>*:lt(3) as the selector and wrapAll()

$(function() {
  $('.cart>*:lt(3)').wrapAll('

');
});

  <form class="cart">
    <button></button>

    <button></button>
    <button></button>
  </form>

result:

  <form class="cart">

      <button></button>

      <button></button>

    <button></button>
  </form>

note:
According to the Documentation for :lt,

As of jQuery 3.4, the :lt pseudo-class is deprecated. Remove it from
your selectors and filter the results later using .slice(). For
example, :lt(3) can be replaced with a call to .slice( 0, 3 ).

So you should use: $('.cart>*').slice(0, 3).wrapAll(...) for 3.4+ versions.


text:
Q: Launch Map App when user double clicks a text address in a application Is it possible to launch Androids Map App when the user double clicks on an address in a text view of another application?
Similar to when you click on a group of numbers Android will open the phone dialer with the number in the phone number text box.
Is it possible this functionality depends on the version of Android?

A: Uri geoUri = Uri.parse("address here");
Intent mapCall = new Intent(Intent.ACTION_VIEW, geoUri);
startActivity(mapCall);


text:
Q: Why is the Manhattan distance (or block distance) appropriate when I have a discrete data set? Why is the Manhattan distance (or block distance) appropriate when I have a discrete data set and the Euclidean distance is appropriate when I have continuous numerical variables?
Thanks for reply

A: I wouldn't always agree with that statement. but here is an intuition why probably the default should be this way.

*

*Euclidean distance is 'as the crow flies'. It is the shortest path if you continuously linear interpolate between these points. The distance from 0 to (1,1) passes through (0.5,0.5) and the distance is $\sqrt{2}$.

*Manhattan distance assumes independent attributes. In particular, no continuous linear independence. If you have a discrete variable, Manhattan is the number of steps you have to do there.

But that is just an intuition, a "rule of thumb"
For example a discrete histogram, I'd rather use a divergence distance.
Or if you consider "money" to be discrete (I would not suggest to do this here), and the number of products bought. There will usually be some linear dependence between these attributes, then Euclidean is likely more appropriate (not that it would make any sense to apply a distance function on quantity,cost without careful feature engineering.)


text:
Q: Cache OpenStreetMap tiles with MapCache I'm trying to cache OpenStreetMap related tile. The corresponding server has separate data related to opeenstreetmap (http://xx.xx.xx.xx/osm). It's an XZY Tiles service. Within the mapcache.xml file I set the source type to be tms service. But when I restart my Apache service I get a message:unknown source type tms for source osm.
Mapcache.xml file:
<?xml version="1.0" encoding="UTF-8"?>

<mapcache >
   <cache name="disk" type="disk">
      <base>C:/ms4w/tmp/ms_tmp/cache/primer3/{tileset}/{z}-{x}-{y}.{ext}</base>
      <!--<symlink_blank/>-->
   </cache>

   <source name="osm" type="tms">
      <getmap>
         <params>
            <FORMAT>image/png</FORMAT>
            <LAYERS></LAYERS>
         </params>
      </getmap>

      <http>
         <url>http://xx.xx.xx.xx/tile/{z}/{x}/{y}.png</url>
      </http>
   </source>

   <tileset name="test">
      <source>osm</source>
      <cache>disk</cache>
      <grid>g</grid>
      <format>PNG</format>
      <metatile>5 5</metatile>
      <metabuffer>10</metabuffer>
      <expires>3600</expires>
   </tileset>

   <default_format>JPEG</default_format>
   <service type="tms" enabled="true">
      <full_wms>assemble</full_wms>
      <resample_mode>bilinear</resample_mode>
      <format>PNG</format>
      <maxsize>4096</maxsize>
   </service>
   <service type="wms" enabled="true">
   </service>
   <service type="wmts" enabled="true"/>
   <service type="kml" enabled="true"/>
   <service type="gmaps" enabled="true"/>
   <service type="ve" enabled="true"/>
   <service type="demo" enabled="true"/>

   <errors>report</errors>
   <lock_dir>C:/ms4w/tmp/ms_tmp/cache/primer2</lock_dir>

</mapcache>

Why does it report that the unknown type is tms if it exists as a defined service?

A: In the MapCache terminology, service refers to protocols used for querying local MapCache and source refers to protocols used for querying remote servers.
XZY Tiles services like OSM can be accessed by MapCache with a REST cache configuration. If you need to cache it locally, you can define a tileset using this REST cache, then a WMS source + cache + tileset refering to this tileset:
<cache name="remote-openstreetmap" type="rest">
   <url>http://xx.xx.xx.xx/tile/{z}/{x}/{inv_y}.png</url>
   <headers><User-Agent>mod_mapcache/1.9dev</User-Agent></headers>
</cache>
<tileset name="remote-openstreetmap">
   <cache>remote-openstreetmap</cache>
   <grid>GoogleMapsCompatible</grid>
</tileset>

<source name="openstreetmap" type="wms">
   <http><url>http://localhost/mapcache?</url></http>
   <getmap><params>
      <format>image/png</format>
      <layers>remote-openstreetmap</layers>
   </params></getmap>
</source>
<cache name="openstreetmap" type="sqlite3">
   <dbfile>/share/caches/osm/openstreetmap.sqlite3</dbfile>
</cache>
<tileset name="openstreetmap">
   <source>openstreetmap</source>
   <format>PNG</format>
   <cache>openstreetmap</cache>
   <grid>GoogleMapsCompatible</grid>
</tileset>

<service type="wms" enabled="true"/>

A: I can read from the documentation https://mapserver.org/mapcache/config.html

A source is a service mod-mapcache can query to obtain image data.
  This is typically a WMS server accessible by a URL. (There are
  currently only WMS, WMTS and mapfile as sources, though others may be
  added later if the need arises, see Data Sources).

The error message is telling that "tms" type of service is not supported as a source. The documentation about how to configure the supported source types is in
https://mapserver.org/mapcache/sources.html#mapcache-sources
You can use tms service as a source with MapProxy https://mapproxy.org/docs/nightly/sources.html.


text:
Q: Converting "Mar 13, 2013 05:30pm" to an NSDate I have the following string "Mar 13, 2013 05:30pm" . I want to convert it into the NSDate object.
I have tried the following way but it is not working.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM:dd, YYYY hh:mm:aa"];
date=[dateFormatter dateFromString:dateString];

A: NSDateFormatter *dFormate = [[NSDateFormatter alloc] init];
[dFormate setDateFormat:@"MM dd, yyyy hh:mma"];
[dFormate setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSString *dateStr = @"Mar 13, 2013 05:30pm";
NSDate *date = [dFormate dateFromString:dateStr];

NSLog(@"Date : %@", date);

A: Try this :-
NSString *stringDate = @"Mar 13, 2013 05:30pm";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd, yyyy hh:mmaa"];
NSDate *date=[dateFormatter dateFromString:stringDate];
NSLog(@"Date : %@",date);

Hope it helps you..


text:
Q: Migration IIS6 to IIS7 - Web Deploy Service Fails To Start I am trying to migrate an entire server from IIS 6 to IIS 7. While there are only 10 web sites, some of them have fairly complex configurations that would be time consuming to do manually (although I have wasted so much time trying to use Web Deploy already, it is starting to look like the better option).
I tried following the instructions outlined in Migrate a Web Site from IIS 6.0 to IIS 7, but on the IIS 6 source server I am running sites that use host header names and the default port 80 conflicts with IIS. So I used the command line to install it on port 6222:
msiexec /i x86_msdeploy.msi /passive ADDLOCAL=ALL LISTENURL=http://+:6222/MSDEPLOY2/

The installation succeeds, however I run net start to start the service as outlined in the article and it fails to start.
net start msdepsvc

The error message was "The Web Deployment Agent Service service terminated with the following error: %%2148734208". I did some research and discovered someone else with the same error message and he said he rebooted the server to fix the issue.
Herein lies my problem: the reason for migration is that the server will not recover from a reboot. I tried rebooting and ended up having to restore the machine from backup in order to get it to boot again (and then of course, MSDeploy was completely gone from the server).
I did some more digging and discovered this more complete MSDeploy article, but the instructions also require the MSDeploy service to be running on the IIS 6 source server.
My questions are -

*

*Is there a way to start the service without requiring a reboot?

*If not, is there a standalone executable that can be used to export the IIS 6 settings without having to run a service?

*Or is there at least a tool that can be used to import the old IIS 6 XML file format into IIS 7?

*Is my only option here to copy the settings manually, and if so is there some kind of a cheat sheet to find where a setting is in IIS 7 based on where it is located in IIS 6?

Update
Due to the lack of response and other alternatives, I ended up migrating the settings manually. IIS 7 didn't require as much of a learning curve as I anticipated and all of the sites seem like they are working as good or better than before even though they are using legacy versions of .NET (2.0 and 3.5).


text:
Q: How to load a4j:outputPanel from DropDown() using ajax call in Richfaces? This is related to richfaces 4.0
I have two dropdown in my webpage. On selecting item on first DropDown, Second DropDown(Invisible previously) is easily rendered on webpage .
On selecting the item in second drop down, I want to render a separate panel(Not able to do this).
Problem is that I can render second DropDown on webpage successfully after selecting item from first dropdown, but no panel is rendered when I am selecting second dropDown item .
My code is as follows :
 <rich:panel header="Select Operation" style="margin-top: 20px;  height: 110px">
            <h:panelGrid columns="1">
                <h:form>
                    <h:panelGrid columns="4">
                        <h:outputLabel value="Operation: " style="font-size: small; font-weight: 900"/>
                        <h:selectOneMenu style="margin-left: 10px; width: 150px" value="#{adminBean.currentType}">
                            <f:selectItem itemValue="0" itemLabel="" />
                            <f:selectItem itemValue="1" itemLabel="Add New User" />
                            <f:selectItem itemValue="2" itemLabel="Manage Balance" />
                            <f:selectItem itemValue="3" itemLabel="Manage Account" />
                            <a4j:ajax event="valueChange" render="second" execute="@this" />
                        </h:selectOneMenu>

                        <h:form>
                            <a4j:outputPanel id="second" layout="block">
                                <h:outputLabel value="Type : " style="margin-left: 130px; font-size: small; font-weight: bold;" rendered="#{not empty adminBean.currentType}"/>
                                <h:selectOneMenu style="margin-left: 10px; width: 150px" value="#{adminBean.currentItem}" rendered="#{not empty adminBean.currentType}">
                                    <f:selectItem itemValue="0" itemLabel="" />
                                    <f:selectItem itemValue="1" itemLabel="Participant" />
                                    <f:selectItem itemValue="2" itemLabel="Administrator" />
                                    <a4j:ajax event="valueChange"  render="rep"  execute="@this" />
                                </h:selectOneMenu>

                            </a4j:outputPanel>
                        </h:form>
                    </h:panelGrid>
                </h:form>

            </h:panelGrid>

        </rich:panel>

        <rich:panel style="margin-top: 20px; min-height: 500px">

            <a4j:outputPanel id="rep">

                <rich:panel rendered="#{not empty adminBean.currentItem}" header="Add Customer">

                    <h:panelGrid columns="2">
                        <a4j:commandButton value="Add New" style="width: 70px"></a4j:commandButton>
                        <a4j:commandButton value="Delete" style="margin-left: 10px; width: 70px"></a4j:commandButton>
                    </h:panelGrid>

                    </rich:panel>
                   </a4j:outputPanel>
            </rich:panel>

As explained above I want id="rep" to be rendered when selecting item from second  .

A: You have two problems:

*

*You have nested forms which result in invalid HTML.

*You should give ID's to your components.

This should be the code fixed (note that I removed all the unnecessary attributes in order to make the page work as styles):
<rich:panel id="pnlContainer">
    <h:panelGrid columns="1" id="grdSingleCol">
        <h:form id="frmData">
            <h:panelGrid columns="4" id="grdData">
                <h:selectOneMenu value="#{adminBean.currentType}">
                    <f:selectItem itemValue="0" itemLabel="" />
                    <f:selectItem itemValue="1" itemLabel="Add New User" />
                    <f:selectItem itemValue="2" itemLabel="Manage Balance" />
                    <f:selectItem itemValue="3" itemLabel="Manage Account" />
                    <a4j:ajax render="second" execute="@this" />
                </h:selectOneMenu>

                <a4j:outputPanel id="second" layout="block">
                    <h:selectOneMenu value="#{adminBean.currentItem}">
                        <f:selectItem itemValue="0" itemLabel="" />
                        <f:selectItem itemValue="1" itemLabel="Participant" />
                        <f:selectItem itemValue="2" itemLabel="Administrator" />
                        <!-- check how to render components outside the form -->
                        <a4j:ajax render=":pnlRepContainer:rep" execute="@this" />
                    </h:selectOneMenu>
                </a4j:outputPanel>
            </h:panelGrid>
        </h:form>
    </h:panelGrid>
</rich:panel>

<rich:panel id="pnlRepContainer">
    <a4j:outputPanel id="rep">
        <rich:panel rendered="#{not empty adminBean.currentItem}"
            header="Add Customer">
            <h:panelGrid columns="2">
                <a4j:commandButton value="Add New" />
                <a4j:commandButton value="Delete" />
            </h:panelGrid>
        </rich:panel>
    </a4j:outputPanel>
</rich:panel>


text:
Q: The maximum value of the two variables function given some constraints. Let:
$$f(x,y)=x^2+2y^2$$
It is required to obtain the maximum value of the above function subject to the constraint $$y-x^2+1=0.$$
I know how to maximize a function of two variables using the usual calculus method of finding the partial derivatives. But given a constraint, i have no idea how to proceed. One thing I tried is to obtain the value of $x^2$ from the constraint and substitute it to the two variable function. In that way, i get a one variable function which is entirely depending on $y$. Then, i tried to differentiate the obtained expression with respect to $y$. This is not giving me the desired result and i am stuck here. Any help would be very beneficial for me. Thanks.

A: Substituting $x^2$ of your constraint equation:
$f(y)= y+1+ 2y^2.$
This function is not bounded above .

A: $$x^2=y+1$$
and the objective function become $$f(y)=y+1+2y^2$$ where we require $y \geq -1$. Notice that $f(y)$ is a convex function.
$$f'(y)=4y+1$$
Hence the turning point is at $-\frac14$ and the function $y$ increases to $\infty$ after that.
In particular, let $(x,y)=(\sqrt{y+1},y)$ where $y>0$, then $f(x,y)=y+1+2y^2$ and it can be arbitarily large and the constraint is satisfied.
To understand this geometrically, plot the curve of $y=x^2-1$ and notice that the curve can go arbitrarily far away from the origin, i.e. $(x^2+y^2)+y^2$ can become arbitrarily large.

A: for simplification you can consider the function $$h(y)=y+1+2y^2$$


text:
Q: if not working with decrement/increment Hi I´m new in php and in one book i found this:
$x = 0;
if ($x-- == 0) echo $x;

in book they write it should write -1 to my page, because decremenet was done after comparison and before the command exho was executed. I understand why it is that, but when I type it into my editor it's giving me error because it's understanding $x-- as one and $x as another variable. Where's problem?

A: Basic Steps :
Step 1: (get Notepad++)
Go to http://notepad-plus-plus.org/ and download Notepad++.
Notepad++ is a free (as in "free speech" and also as in "free beer") source code editor and Notepad replacement that supports several languages. Running in the MS Windows environment, its use is governed by GPL License.
Step 2: (type the code)
type and save as "filename.php" in "www directory"
<?php

$x = 0;
if ($x-- == 0) echo $x;

?>

Step 3: (enJoy !)
Check the result

Expected Output :
  -1 //  this is what i got! :D

A: $x-- is postdecrement that is the $x value will be still 0. when you went away from the statement then only the $x value should be change. so if statement is working fine. the echo value will be -1.
7-isnotbad answer is correct.


text:
Q: Ada - one dimensional array operations In reference to John Barnes' book "Programming in Ada 2012" (ISBN: 978-1-107-42481-4), P. 138 (section 8.6).
procedure ArrayOps is
  type Bit_Row is array (Positive range <>) of Boolean;

  A, B : Bit_Row (1 .. 4);

  T : constant Boolean := True;
  F : constant Boolean := False;
begin
  A := (T, T, F, F);
  B := (T, F, T, F);

  A := A and B;
end ArrayOps;

I've added a simple wrapper around the minimal fragment the author provides, and this seems to compile and run as expected.
The author states that this can be done with "Many of the operators", implying arithmetical such as +, *, - and /.
I have attempted to convert this to the addition operator using Integer data types, but alas this does not compile...
procedure ArrayOps is
  type Int_Row is array (Positive range <>) of Integer;

  A, B : Int_Row (1 .. 4);

  T : constant Integer := 1;
  F : constant Integer := 0;
begin
  A := (T, T, F, F);
  B := (T, F, T, F);

  A := A + B;
end ArrayOps;

The compiler error states: arrayops.adb:12:10: there is no applicable operator "+" for type "Int_Row" defined at line 2.  That is the only error.  Clearly something is missing from my code, but the book doesn't mention this topic ever again.  How may I enable array operations for operators other than the boolean operators?
EDIT:
I have amended the code as per @egilhh's answer, as that seems to be the minimal set of changes to solve the basic problem.
procedure ArrayOps is
  type Int_Row is array (1 .. 4) of Integer;

  function "+"(Left, Right : Int_Row) return Int_Row
  is
     Result : Int_Row;
  begin
     for I in Int_Row'Range loop --'
        Result(I) := Left(I) + Right(I);
     end loop;
     return Result;
  end "+";

  A, B : Int_Row;

  T : constant Integer := 1;
  F : constant Integer := 0;
begin
  A := (T, T, F, F);
  B := (T, F, T, F);

  A := A + B;
end ArrayOps;

This now works.  However, I have accepted DeeDee's answer as that may be a best practice solution.  Kudos to both :)

A: With "many operators" the book refers to the logical and relational operators. Only these operators are implicitly defined for one-dimensional array types as required by the language standard (see RM 4.5.1 (2) and RM 4.5.2 (1)).
For other operators, you'll need to implement them yourself:
arrayops.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure ArrayOps is

   type Int_Row is array (Positive range <>) of Integer;

   A, B : Int_Row (1 .. 4);

   T : constant Integer := 1;
   F : constant Integer := 0;

   ---------
   -- "+" --
   ---------

   function "+" (A, B : Int_Row) return Int_Row is
   begin

      if A'Length /= B'Length then
         raise Constraint_Error with "array lengths do not match";
      end if;

      declare
         Result : Int_Row (1 .. A'Length);
      begin
         for I in Result'Range loop
            Result (I) := A (A'First + I - 1) + B (B'First + I - 1);
         end loop;
         return Result;
      end;

   end "+";

   ---------
   -- Put --
   ---------

   procedure Put (A : Int_Row; Width : Natural := 0) is
      use Ada.Integer_Text_IO;
   begin
      for I in A'Range loop
         Put (A (I), Width);
      end loop;
   end Put;

begin

   A := (T, T, F, F);
   B := (T, F, T, F);

   Put (A, 2); New_Line;
   Put (B, 2); New_Line;

   A := A + B;

   Put ("--------- +"); New_Line;
   Put (A, 2); New_Line;

end ArrayOps;

output
 1 1 0 0
 1 0 1 0
--------- +
 2 1 1 0

A: "Many" does not mean "all"... Specifically he mentions  and, or, xor and not for one-dimensional Boolean arrays. Of course, those are just the predefined ones; there's nothing stopping you from defining your own operators. Take a look at P. 169 (section 10.2).
function "+"(Left, Right : Int_Row) return Int_Row
is
   Result : Int_Row;
begin
   for I in Int_Row'Range loop --'
      Result(I) := Left(I) + Right(I);
   end loop;
   return Result;
end "+";


text:
Q: I need root to run ./a.out (C) program cd /media/k4li/data2/C
gcc program.c
./a.out

running ./a.out:
bash: ./a.out: Permission denied

if I enter sudo ./a.out i get:
 sudo: ./a.out: command not found

A: Because NTFS doesn't store or use "Linux" file permissions the kernel emulates them. You set the entire mount partitions permissions at mount time. You have two option.

*

*Remount the NTFS partition, setting the permissions to something less restrictive. This is the least secure option.

*Move the executable to your Linux partition, then chmod it, then run it. There are more steps here but this is the most secure option.
2 is more secure then 1 because you only change the permissions of one file, not the entire partition.

A: You need to set a.out's permissions to executable - use:
sudo chmod +x a.out

And then try running it again.
Edit: Need to use sudo on chmod.


text:
Q: Is that possible to have open dialog window inside child window in Silverlight? I need to have OpenDialog window being inside browser window of Silverlight application. I am wondering if it possible. Any help is highly appreciated!
Below is the code I have to open child window and OpenDialog:
 private void openChildWindow_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Add_ChildWindow ap = new Add_ChildWindow();
        ap.Show();

          OpenFileDialog openFileDialog1 = new OpenFileDialog();
        // Set filter options and filter index.
        openFileDialog1.Filter = "Packages (*.sprj)|*.sprj|Packages (*.sprj)|*.sprj";
        openFileDialog1.FilterIndex = 1;

        openFileDialog1.Multiselect = true;

        // Call the ShowDialog method to show the dialog box.
        bool? userClickedOK = openFileDialog1.ShowDialog();

        // Process input if the user clicked OK.
        if (userClickedOK == true)
        {
            // Open the selected file to read.
            //textBox1.Text = openFileDialog1.File.Name;
            System.IO.Stream fileStream = openFileDialog1.File.OpenRead();

            using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
            {
                // Read the first line from the file and write it the textbox.
               // tbResults.Text = reader.ReadLine();
            }
            fileStream.Close();
        }
    }

A: An Open Dialog window is a system window. Silverlight being sandboxed has to use the system open dialog I believe.
In other words, I don't think this is possible.


text:
Q: how to delete an item from shopping cart by button click in android I can delete an item from shopping list through long press on the selected item by the following code
  listcart.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
           @Override
           public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

               model=d.get(i);
               final String orderno=model.getOrderno();
               AlertDialog.Builder msg=new AlertDialog.Builder(CartActivity.this)
                       .setTitle("Delete Item")
                       .setMessage("Are you sure delete this item "+model.getItemname())
                       .setIcon(R.drawable.applogo)
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialogInterface,int i){
                               DBLite db=new DBLite(CartActivity.this);
                               db.DeleteItem(orderno);
                               d=new ArrayList<>(db.GetCart(CartActivity.this));
                               adapterCart=new Cart_Adapter(CartActivity.this,d);
                               listcart.setAdapter(adapterCart);
                               txtOrderTotal.setText(String.valueOf(db.GetSum()));

                           }
                       }).setNegativeButton("No",null);
               msg.create();
               msg.show();
               return false;
           }
    });

I want to delete this item by clicking (x) image. How can I customize that code for that purpose, like the image below:

A: Make a button inside your item layout. Take its reference in your Cart_Adapter adapter class and do this inside getView() method of your adapter (if it is BaseAdapter or ArrayAdapter). But if it is recyclerview adapter then write this inside onBindView() method of that:
    viewholder.deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // write code here to delete item and refresh adapter
        }
    });

A: There is no need to setup your adapter again, if it's already loaded. Try this code into your dialog positive button of your AlertDialog() which will be called from your onBindViewHolder() method in your adapter class.
 <yourViewHolderObject>.deleteIcon.setOnClickListener(new AdapterView.OnClickListener() {
  // like: deleteIcon = view.findViewById(R.id.deleteIcon);
       @Override
       public boolean onClick(View view, int i) {

           model=d.get(i);
           final String orderno=model.getOrderno();
           AlertDialog.Builder msg=new AlertDialog.Builder(CartActivity.this)
                   .setTitle("Delete Item")
                   .setMessage("Are you sure delete this item "+model.getItemname())
                   .setIcon(R.drawable.applogo)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialogInterface,int i){
                           DBLite db=new DBLite(CartActivity.this);
                           db.DeleteItem(orderno);
                           // Also delete this item from your current list
                           listcart.remove(model);
                           d=new ArrayList<>(db.GetCart(CartActivity.this));
                           adapterCart=new Cart_Adapter(CartActivity.this,d);
                           //listcart.setAdapter(adapterCart); // exclude this
                           adapterCart.notifyDataSetChanged(); // include this
                           // this line your reload and update your list
                           txtOrderTotal.setText(String.valueOf(db.GetSum()));

                       }
                   }).setNegativeButton("No",null);
           msg.create();
           msg.show();
           return false;
       }
});

A: i found a way and it works. i deal with delete button through cartAdapter activity in which c=context , ass=arrayList<>
   viewHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlertDialog.Builder msg=new AlertDialog.Builder(c)
                    .setTitle("Delete Item")
                    .setMessage("Are you sure delete this item "+data.getItemname())
                    .setIcon(R.drawable.applogo)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface,int i){
                            DBLite db=new DBLite(c);
                            db.DeleteItem(data.getOrderno());
                            ass=new ArrayList<>(db.GetCart(c));
                            adapterCart=new Cart_Adapter(c,ass);
                            listcart.setAdapter((ListAdapter) adapterCart);
                            txtOrderTotal.setText(String.valueOf(db.GetSum()));

                        }
                    }).setNegativeButton("No",null);
            msg.create();
            msg.show();
        }
    });


text:
Q: not losing the focus event on jquery I have this html:

 click me

 click me

 click me

<textarea id="myText">
 hey
</textarea>

javascript:
$("textarea").live("focus",function(){
 $("#myDiv").css("display","block");
});

$("textarea").live("blur",function(){
 $("#myDiv").css("display","none");
});

on textarea focus I set the div style to display:block so we can click the javascript link
the script will add text to the textarea
on textarea blur I set the div style to display:none
I need to see the div links so I can add them more then 1 time
but what happens is that when I click a link the div sets to display:none because I am focusedout of the textarea

A: You can prevent loosing focus like this:
$('a').mousedown(function() { return false; })
      .click(function() { alert('works'); });

Code: http://jsfiddle.net/2qMFX/7/

A: I recommend that you let user close the div on-demand. This means that on entering focus to the <textarea>, you display div, and on div you have a close button, that use can click and close.


text:
Q: Why is executable size of a MFC dialog built with VS 2012 nearly 3X the size of one built with VS 2005? I did an experiment by building the default MFC dialog using VC++ 6.0, VS 2005, VS 2008, VS 2010, and VS 2012.
Each was built using MFC in a static library because the potential users generally don't have privileges to install the required runtimes.  Each used multi-byte char set, was built in release mode, and had support for Winsock.  This was on a Windows 7 machine.  All are 32-bit apps.
The VS 2012 app had the _AFX_NO_MFC_CONTROLS_IN_DIALOGS switch defined to make it smaller which did almost nothing.  Here are the results:
VC++6.0    204 KB
VS 2005    304 KB
VS 2008   1690 KB
VS 2010   1724 KB
VS 2012   3888 KB

I was amazed to find that the app built with VS 2012 was over 10 times the size of the one built with 2005.  Is all of this due to security enhancements?
My company is phasing out all but VS 2010 and VS 2012 due to security vulnerabilities in the older IDE's.  I typically build and maintain large and complicated MFC dialog-based apps, and many of them run simultaneously, so I'd like to minimize their total memory footprint.
Besides dumping MFC and moving to C#/WPF or QT, each of which has its own downsides;

*

*is there some magic compiler setting I can use with VS 2012 to remove some of this bloat?

A: This is a known issue. Here are some links for you to look at:

*

*Reducing the Size of Statically-linked MFC Applications in VC11 (I think you already did this without results).

*Statically linked release MFC EXE size in Visual C++ 2010 vs 2008

*How to make small statically linked MFC EXEs in Visual C++ 2010


text:
Q: What is code to count last row and add cell data to new blank row The code copies data from cell M4 and to cell L45, which is good but if I change the date in M4 and run the script it will overwrite cell L45 with the new info instead of copying to the next blank row below (cell L46)
What is the adjustment needed and where would it go in the script
Here is code:
function moveValuesOnly() {

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var source = ss.getRange('M4');
 source.copyTo(ss.getRange('L45'), {contentsOnly: true});

A: This function will append any changes in 'M4' to the bottom of column L.
function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()!='Sheet1') {return;};//edit Sheet name for your requirements
  if(e.range.getA1Notation()=='M4') {
    e.range.getSheet().getRange(getColumnHeight(12,sh,e.source) + 1,12).setValue(e.value);
  }
}

function getColumnHeight(col,sh,ss){
  var ss=ss || SpreadsheetApp.getActive();
  var sh=sh || ss.getActiveSheet();
  var col=col || sh.getActiveCell().getColumn();
  var rg=sh.getRange(1,col,sh.getLastRow(),1);
  var vA=rg.getValues();
  while(vA[vA.length-1][0].length==0){
    vA.splice(vA.length-1,1);
  }
  return vA.length;
}


text:
Q: Do stator windings on a permanent-magnet synchronous three-phase ac motor have sinusoidal distributions? In motor-drives textbooks (e.g Ned Mohan's Electric Motor Drives), the text states that the stator windings on ac machines (e.g. PMAC three-phase motors and induction machines) are, in theory, sinusoidally distributed in the air gap. That is, the conductor density as a function of the mechanical angle (for a two-pole motor) can be written
$$ n_s(\theta)=\frac{N_s}{2} \sin(\theta) $$
where \$N_s\$ is the number of turns. This is not possible in practice due to the slots, but it is approximated.
Is this true for modern PMAC motors ? If we consider one of the three phases, are there more conductors per angle at 90 and 270 degree angles from the magnetic axis than there are at f.ex 60 and 120 degrees ? I tried to find photos, but could not so easily see this...

A: Yes:
A PMAC motor has an (approximately) sinusoidally distributed stator winding to produce sinusoidal back EMF waveforms. (Similarly a 3-phase AC induction motor does as well).
A "brushless DC" motor intended for six-step commutation may have trapazoidally distributed windings.
A good summary is Here
An interesting graphical representation with animation is Here


text:
Q: Android + Scala + library project: NoClassDefFound I have a similar issue as in the SO question below, but with scala as my language of choice:
Android project referencing "normal" java project in eclipse since sdk tools update 17
Basically, if I setup a regular android project using java,
a regular java library project and a 'glue' android library project as described in the link above, everything works fine and I can use code from my referenced regular java project.
However, if I try to repeat the same procedure using scala projects I get a noclassdeffound exception when launching. (If I move the code form the regular referenced project into the main android project the error disappears and everything works.)
Any hints on what to look for? Anyone doing the same with success?


text:
Q: JDBC PreparedStatement doesn't work but doesn't show any errors i'm using a Tomcat 7 and i try to fill my MySQL Database with Java and JDBC. It worked with a small sample table(Tutorial link below) but now i try to fill my own values and it doesn't work anymore. Even the small example doesn't work. The weird thing is, i don't get any kind of errors or something. It just does nothing. I had to throw "errors" by myself to locate the problem. I think it's the PreparedStatement. Most of the time the last PreparedStatement.
I searched 2 days for a solution but without success. Maybe i forgot something or i deleted something while i was looking for the solution. I appriciate every kind of suggestions.
I used this tutorial: http://www.vogella.com/tutorials/MySQLJava/article.html and everything was fine. With my table and my insert code, it doesn't work.
Here is my code for the MySQL connection. That's everything inside the try part. I hope you find something or have some tips or something else.
  Class.forName("com.mysql.jdbc.Driver");
  //I tried the Connection with and without port. No difference
  connect = DriverManager
          .getConnection("jdbc:mysql://localhost:3306/dbname?"
              + "user=ihaveanuser&password=ihaveapassword");
  statement = connect.createStatement();

  preparedStatement = connect.prepareStatement("insert into dbname.data values (default, ?, ? , ?, ?, ?, ?, ?, ?, ?,?)");

  //These are just some random inserts based on the table.
  //With the inserts i want to use it doesn't work neither.
  int tempint =  12345;
  double tempdouble = 12.12345;
  preparedStatement.setInt(1,tempint);
  preparedStatement.setInt(2,tempint);
  preparedStatement.setString(3,"test");
  preparedStatement.setInt(4, tempint);
  preparedStatement.setInt(5, tempint);
  preparedStatement.setString(6, "test");
  preparedStatement.setDouble(7, tempdouble);
  preparedStatement.setDouble(8, tempdouble);
  preparedStatement.setInt(9, tempint);
  preparedStatement.setString(10, "test");
  preparedStatement.setString(11, "test");

  preparedStatement.executeUpdate();

Please don't hesitate to ask me questions.
Regards
Eric


text:
Q: Error while binding a socket : NSPOSIXErrorDomain Code=1 "Operation not permitted" I'm trying to implement GCDAsyncSocket to mac os x (Mojave 10.14.3) application to listen data from localhost:port.
The problem is no matter what port I choose I always get this error:
Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"
UserInfo={NSLocalizedDescription=Operation not permitted,
NSLocalizedFailureReason=Error in bind() function}

I've already tried this, but it didn't work.
Here is my implementation in AppDelegate.mm:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:(id<GCDAsyncSocketDelegate>) self delegateQueue:dispatch_get_main_queue()];
    connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
    isRunning = NO;
    NSError *err = nil;
    if (![listenSocket connectToHost:@"localhost" onPort:12345 error:&err]){
        NSLog(@"I goofed: %@", err);
    }
}

-(void)getData{
    if(!isRunning)
    {
        int port = 12345;
        if(port < 0 || port > 65535)
        {
            port = 0;
        }
        NSError *error = nil;
        if(![listenSocket acceptOnPort:port error:&error])
        {
            NSLog(@"error: %@", FORMAT(@"Error starting server: %@", error));
            return;
        }
        NSLog(@"error: %@", FORMAT(@"Echo server started on port %hu", [listenSocket localPort]));
        isRunning = YES;
    }
    else
    {
        // Stop accepting connections
        [listenSocket disconnect];

        // Stop any client connections
        NSUInteger i;
        for(i = 0; i < [connectedSockets count]; i++)
        {
            [[connectedSockets objectAtIndex:i] disconnect];
        }
        NSLog(@"Stopped Echo server");
        isRunning = false;
    }
}

- (void)onSocket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    [connectedSockets addObject:newSocket];
}

- (void)onSocket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(FORMAT(@"Accepted client %@:%hu", host, port));
    NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
    NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];

    [sock writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];

    [sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}

- (void)onSocket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if(tag == ECHO_MSG)
    {
        [sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
    }
}

- (void)onSocket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
    NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
    if(msg)
    {
        NSLog(@"msg %@", msg);
    }
    else
    {
        NSLog(@"Error converting received data into UTF-8 String");
    }

    // Even if we were unable to write the incoming data to the log,
    // we're still going to echo it back to the client.
    [sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}

- (NSTimeInterval)onSocket:(GCDAsyncSocket *)sock
  shouldTimeoutReadWithTag:(long)tag
                   elapsed:(NSTimeInterval)elapsed
                 bytesDone:(NSUInteger)length
{
    if(elapsed <= READ_TIMEOUT)
    {
        NSString *warningMsg = @"Are you still there?\r\n";
        NSData *warningData = [warningMsg dataUsingEncoding:NSUTF8StringEncoding];

        [sock writeData:warningData withTimeout:-1 tag:WARNING_MSG];

        return READ_TIMEOUT_EXTENSION;
    }

    return 0.0;
}

- (void)onSocket:(GCDAsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort]));
}

- (void)onSocketDidDisconnect:(GCDAsyncSocket *)sock
{
    [connectedSockets removeObject:sock];
}

I'm not sure about if my implementation is wrong or I should get any kind of permissions granted.
Any help would be appreciated!

A: You should enable its network capability of the App Sandbox
macOS Catalina Version 10.15.3:


text:
Q: How can i access FormArray inside formGroup inside another formGroup? I have an array of data as follows:
[
    {
      id: "1",
      name: "task1",
      taskForms: [
        {
          id: "8782",
          name: "ProcedureComment",
          sortOrder: null,
          description: "Comment for 'Procedure end / Suture' task",
          label: null
        },
        {
          id: "20",
          name: "form20",
          description: "form20 description",
          label: "form20 lable"
        }
      ]
    },
    {
      id: "2",
      name: "task2",
      taskForms: [
        {
          id: "87822",
          name: "ProcedureComment2",
          sortOrder: null,
          description: "Comment for 'Procedure end / Suture' task2",
          label: null
        },
        {
          id: "202",
          name: "form202",
          description: "form202 description",
          label: "form202 lable"
        }
      ]
    }
  ];

and I want to convert taskForms to FormArray().
Do I have to mark tasks as formGroup and then mark taskForms as FormArray? How do I do this?
public formGroup = new FormGroup({
    tasks: new FormControl([])
//==>> i need it first as FormControl then i want to convert it and write data inside.
  });

I tried:
    this.formGroup.setControl('tasks', this.formBuilder.group(tasks));

but I couldn't make it work.

A: FormArray in Nested FormGroup
You can just use the FormBuilder to make your life easier:
constructor(private fb: FormBuilder) {}

ngOnInit(): void {
  this.formGroup = this.fb.group({
    nested_formgroup: this.fb.group({
      array: this.fb.array([
        { example: ['']}
      ])
    })
  })
}

Result
{
  "nested_formgroup": {
    "array": [
      {
        "example": ""
      }
    ]
  }
}

Load the Data
To load the data you will just need to map your object to the value members of the FormControls.
loadData() {
  this.someService.getData().subscribe(
    data => {
      this.formGroup.get('nested_formgroup').get('array').value[0].example = data.example
    }
  )
}

Here's an example on Stackblitz for you to test/play with.


text:
Q: With imake, how to I handle a header file that is generated? I have a C header file, used by a program, that is generated from a script that takes a text file as input.
The problem is that when xmkmf -a is run, I get
myprogram.c:114:25: fatal error: generated_header.h: No such file or directory

The command to generate the header is like
myscript header_input.txt > generated_header.h

How do I handle a header being generated with imake?
I tried adding rules that say
 myprogram.c: generated_header.h

but the make depend gets ran and fails before this rule is ran to generate the file. (Things work fine if I just do xmkmf rather than xmkmf -a but the probably here is that running xmkmf -a is the standard way of using imake.)
I'm not experienced with imake and there doesn't seem to be a lot of documentation so I'm stumbling. Any help would be appreciated.

A: Found a workaround through comments. Question is still open for a more "correct" answer.

I tried adding rules that say
myprogram.c: generated_header.h
but the make depend gets ran and fails before this rule is ran to generate the file.

The above tells imake that myprogram.c needs a file generated_header.h. It is a dependency.
What it doesn't tell imake is how to generate generated_header.h.
For that, you would need something along these lines:
generated_header.h: header_input.txt
    myscript header_input.txt > generated_header.h

Note that the "recipee" ("how to generate generated_header.h") needs to be indented with a tab, not spaces. Make (and imake) do make a difference between tab and space that way.
The general syntax is:
target: dependency [dependency...]
    recipee
    [recipee...]

In this regard, imake isn't different from standard make. Actually, imake is "make with C preprocessor running first", so reading the generic make manuals might be helpful.