text:
Q: What is a good design pattern for generating an Excel (xlsx) file in code? See my Update at the bottom for more.

I occasionally have projects where I have to output some data as an Excel file (xlsx format).  The process is usually:

*

*User clicks some buttons in my application

*My code runs a DB query and processes the results somehow

*My code generates an *.xlsx file using either the Excel com interop libraries or some third-party library (e.g., Aspose.Cells)
I can easily find code examples for how to do this online, but I am looking for a more robust way to do this.  I'd like my code to follow some design principles to ensure that my code is maintainable and easily understandable.

Here is what my initial attempt to generate an xlsx file looked like:
var wb = new Workbook();
var ws = wb.Worksheets[0];
ws.Cells[0, 0].Value = "Header";
ws.Cells[1, 0].Value = "Row 1";
ws.Cells[2, 0].Value = "Row 2";
ws.Cells[3, 0].Value = "Row 3";
wb.Save(path);

Pros: Not much.  It works, so that's good.
Cons:

*

*Cell references are hardcoded, so I have magic numbers littered throughout my code.

*It's difficult to add or remove columns and rows without updating many cell references.

*I need to learn some third-party library.  Some libraries are used like other libraries, but there can still be problems.  I had a problem where the com interop libraries use 1-based cell referencing whereas Aspose.Cells uses 0-based cell referencing.

Here is one solution that addresses some of the cons I listed above.  I wanted to treat a table of data as its own object that can be moved around and changed without digging into cell manipulation and disturbing other cell references.  Here is some pseudocode:
var headers = new Block(new string[] { "Col 1", "Col 2", "Col 3" });
var body = new Block(new string[,]
    {
        { "Row 1", "Row 1", "Row 1" },
        { "Row 2", "Row 2", "Row 2" },
        { "Row 3", "Row 3", "Row 3" }
    });

body.PutBelow(headers);

As a part of this solution, I'll have some BlockEngine object that takes a container of Blocks and performs the cell manipulations required to output the data as an *.xlsx file.  A Block object can have formatting attached to it.
Pros:

*

*This removes most of the magic numbers that my initial code had.

*This hides a lot of cell manipulation code, although cell manipulation is still required in the BlockEngine object that I mentioned.

*It's much easier to add and remove rows without effecting other parts of the spreadsheet.

Cons:

*

*It's still difficult to add or remove columns.  If I wanted to swap the position of columns two and three, I'd have to directly swap the cell contents.  In this case that'd be eight edits, and thus eight opportunities to make a mistake.

*

*If I have any formatting in place for those two columns, I have to update that as well.

*This solution doesn't support horizontal block placement; I can only place one block below another.  Sure I could have tableRight.PutToRightOf(tableLeft), but that would cause problems if tableRight and tableLeft had different numbers of rows.  To place tables, the engine would have to be aware of every other table.  This seems unnecessarily complicated to me.

*I still need to learn third-party code, though through a layer of abstraction via Block objects and a BlockEngine the code will be less tightly-coupled to the third-party library than my initial attempt.  If I wanted to support lots of different formatting options in a loosely-coupled way, I'd probably have to write a lot of code; my BlockEngine would be a huge mess.

Here is a solution that takes a different route.  Here's the process:

*

*I take my report data and generate an xml file in some format that I choose.

*I then use an xsl transformation to convert the xml file to an Excel 2003 XML Spreadsheet file.

*From there I simply convert the xml Spreadsheet to an xlsx file using a third party library.
I found this page that describes a similar process and includes code examples.
Pros:

*

*This solution requires almost no cell manipulation.  You instead use xsl/xpath to do your manipulations.  In order to swap two columns in a table, you move the whole columns in the xsl file unlike my other solutions which would require cell-swapping.

*While you still need a third-party library that can convert an Excel 2003 XML Spreadsheet to an xlsx file, that's about all you'll need the library for.  The amount of code you need to write that would call into the third-party library is tiny.

*I think this solution is the easiest to understand and requires the least amount of code.

*

*The code that creates the data in my own xml format will be simple.

*The xsl file will be complicated only because the Excel 2003 XML Spreadsheet is complicated.  However it's easy to check the output of the xsl file: just open the output in Excel and check for error messages.

*It's easy to generate sample Excel 2003 XML Spreadsheet files: just create a spreadsheet that looks like your desired xlsx file, and then save it as an Excel 2003 XML Spreadsheet.

Cons:

*

*Excel 2003 XML Spreadsheets don't support certain features.  You can't autofit column widths for instance.  You can't include images in headers or footers.  If you're going to export the resultant xlsx file to pdf, you can't set pdf bookmarks.  (I hacked together a fix for this using cell comments.).  You have to do this using your third-party library.

*Requires a library that supports Excel 2003 XML Spreadsheets.

*Uses an 11-year old MS Office file format.

Note: I realize that xlsx files are actually zip files containing xml files, but the xml formatting seems too complicated for my purposes.

Finally, I've looked into solutions involving SSRS, but it seems too bloated for my purposes.

Back to my initial question, what is a good design-pattern for generating Excel files in code?.  I can think of a few solutions, but none seem to stick out as ideal.  Each has drawbacks.

Update: So I tried both my BlockEngine solution and my XML Spreadsheet solution for generating similar XLSX files.  Here are my opinions of them:

*

*The BlockEngine solution:

*

*This simply requires too much code considering the alternatives.

*I found it too easy to overwrite one block with another if I had an offset wrong.

*I originally stated that formatting could be attached at the block level.  I found this to be not much better than doing the formatting separately from the block content.  I can't think of a good way to combine the content and the formatting.  Nor can I find a good way to keep them separate.  It's just a mess.

*The XML Spreadsheet solution:

*

*I'm going with this solution for now.

*It bears repeating that this solution requires much less code.  I'm effectively replacing the BlockEngine with Excel itself.  I still do need a hack for features like bookmarks and page breaks.

*The XML Spreadsheet format is finicky, but it's easy to make a small change and compare the results to an existing file in your favorite Diff program.  And once you figure out some idiosyncrasy, you can put it in place and forget about it from there.

*I'm still concerned that this solution relies on an older Excel file format.

*The XSLT file I created is easy to work with.  Dealing with formatting is much simpler here than it is with the BlockEngine solution.

A: If you really want something that works well for you, then I suggest you get used to the idea of "unnecessarily complex"... that's the nature of dealing with Microsoft Office file formats.
I (sort of) like your idea of "blocks"... I would make sub-classed block objects, like Table, with Columns and Rows independent of the notion of cells. Then use your block engine to convert these to XSLS files.
I've used the OpenXML SDK successfully in the past, but don't try to read the documentation and start from scratch. Instead, create an exact copy in Excel of what you want, save it, and inspect it using the provided Document Reflector tool. It will give you the C# code you need to create the document, which you can then learn from and modify.

A: Here is a solution I have used often in the past:

*

*create a regular Excel document (typically in xlsx format) as as template, containing all column headers, including their title and a default formatting for the columns and maybe formatting for title cells.

*embed that template into the resources of your program. At runtime, the first step is to extract the template as a new file and place it into the destination folder

*use Interop or a third party library to fill the data into the newly created xlsx. Do not refer to hardcoded column numbers, instead use some metadata (for example the column headers) to identify the correct columns.
Pros:

*

*something like your Block approach now works better. For example, column swapping: no need to change anything in your block code, since the the correct columns are identified by their headers

*as long as your columns have a unique formatting, most of the formatting can be done directly in Excel, by manipulating your template. That gives you a WYSIWYG feeling, together with the freedom to use any formatting option available in Excel without the need of writing code for it
Cons:

*

*you still need to make use of a third party lib or Interop. Did I mention that Interop is slow?

*when the column headers change in your template, you need to adapt also your code (but that can easily detected by having a validation routine which signals if there are expected columns missing)

*when you need dynamic formatting of different cells in the same column, you still have to deal with that in code
As a general hint, whatever approach you choose: it has advantages to separate layout from content and to make use of declarative solutions.

A: There are two things to consider:

*

*Complexity of creating a file in a given format

*Susceptibility of code to breakage when the structure of content of the file needs to change.

Regarding the first:
If the spreadsheets you need to generate don't contain any formatting or formulas, then you it is pretty straight-forward to generate a CSV or Tab-Delimited file instead of an actual XLSX.  Excel opens these files, often by default on a lot of PCs.  This won't help you with hard coding around columns and rows but it will save you the extra work of manipulating the Excel object model.
If you need formatting or formulas, then working with the Excel object model is a reasonable way to go, especially if you build a spreadsheet that isn't too "hard-coded" itself.  In other words, if your spreadsheet uses relative formulas and range names appropriately then it can go together with less hard coding of magic numbers.
Regarding the second:
You can work through cell by cell with hard-coded row and column references, or you can work with arrays/List collections and for loops to generalize the population of cells.


text:
Q: Trouble displaying results of sub query with php using salesforce SOAP api and partner wsdl Here's a generic query sample that represents my problem.
$query = "SELECT Account.Name, Name from Contract WHERE AccountId = '001U0000003q6scIAA'";
$response = $mySforceConnection->query($query);

foreach ($response->records as $record) {
$sObject = new SObject($response->records[0]);
var_dump($sObject);
echo $sObject->sobjects[0]->Name."
\n";
echo $record->fields->Name."
\n";
echo "*******************************
\n";
echo "*******************************
\n";
}

The problem is that the Account.Name field will not display. Just in case my entire method is wrong, The idea is to grab all of the contracts assigned to a specific account and display both the account name and the pertinent info from the contract. (so far all contract fields display perfectly. Just can't display the account name)
Thanks for the assistance in advance!
Here's the var_export().. (I removed all of my custom fields)
SObject::__set_state(array( 'type' => 'Contract', 'fields' => stdClass::__set_state(array(
'AccountId' => '001U0000003q6scIAA', 'Name' => 'test contract', '1' =>
SObject::__set_state(array( 'type' => 'Account', 'fields' => stdClass::__set_state(array(
'Name' => 'test Account name', )), )), )), ))

Here's the var_dump() ...
object(SObject)#5 (2) { ["type"]=> string(8) "Contract" ["fields"]=> object(stdClass)#1871 (14) {
["AccountId"]=> string(18) "001U0000003q6scIAA" ["Name"]=> string(18) "Test Contract Name"
["1"]=> object(SObject)#1869 (2) { ["type"]=> string(7) "Account" ["fields"]=> object(stdClass)#1870 (1) { ["Name"]=> string(15) "Account Name" } } } }

A: So I finally found something that put me on the right path. here's how I solved it...
foreach ($response->records as $record) {
    echo $record->fields->{1}->fields->Name."
\n";
    echo $record->fields->Name."
\n";
    echo "*******************************
\n";
    echo "*******************************
\n";
}

I had tried this approach originally but without the {} which gave an error. So all you have to do is look at the print_r() output, change the number to the number it gives you here - ["1"]=> object(SObject)#1869 and this query will show!
Thanks Daan for trying to help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add @ Page attributes from code behind on button click Long story short, a function on my page causes an error of "There is no MTS object context" when I try to execute it, without explicitly stating AspCompat="true":
< %@ Page Language="C#" AspCompat="true" %>
My questions is is it at all possible to apply AspCompat="true" from code behind for the duration of the function and then remove it again (or not, I can simply redirect)?
I need AspCopat NOT set to true at any other time BUT when the function is executed because it interferes with my Global.asax/Application_Error causing it not to fire at all, hence I can't error log properly.
(The function above needing aspcompat being true is a pdf generating 3rd party library)

A: It seams not possible to achieve this.


text:
Q: What does clipping at Canon or FinePix ISO image mean? I'm trying to review about the camera noise.
Also I have reference as following  http://www.cs.tut.fi/~foi/
But I want to know what does clipping mean at the following code.
:code
%% ====================================================================================================================================
            %% LOAD BITMAP/RAW IMAGE    %  raw-data images which are loaded below can be downloaded from http://www.cs.tut.fi/~foi/sensornoise.html
            %% ====================================================================================================================================
            if 1 %% load "noise-free" image and add noise   (OTHERWISE LOAD RAW DATA, SEE BELOW)
                add_noise=1;                % add noise to image
                a=0.1^2;   b=0.04^2;        % noise parameters a,b
                %    a=0.1^2;   b=0.02^2;       % noise parameters a,b
                %    a=0.0^2;   b=0.2^2;        % noise parameters a,b
                %    a=(1/30);  b=0.1^2;        % noise parameters a,b

                clipping_below=1;   %  on/off   [keep off for pure-poissonian (no gaussian terms) noise, since there are no negative errors]
                clipping_above=1;   %  on/off
                prior_density=1;                 %  type of prior density to use for ML    (0)
                %                                %    1: zero_one uniform prior density [0,1];

                %     y=im2double(imread('image_man1024.tiff'));
                %     y=im2double(imread('image_testpat1024.tiff'));
                y=im2double(imread('y_piecewise.tif'));
                %     y=im2double(imread('y_piecewise_fibo.tif'));

            else %%  RAW  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                add_noise=0;  %% DO NOT ADD NOISE TO RAW-DATA (IT HAS ENOUGH NOISE ALREADY! :) )
                clipping_below=1;  %%%% on off   %% RAW-DATA IS ASSUMED TO BE CLIPPED FROM ABOVE AND BELOW
                clipping_above=1;  %%%% on off
                prior_density=0;                 %  type of prior density to use for ML    (0)
                %                                %    0: zero_infty uniform prior density (R+);  (default, use this for raw-data)

A: Clipping in general is what happens when a value exceeds some threshold and is forced to that threshold. Also known as saturation (when it's accidental), clamping (when deliberate) and others.
It's common in digital systems, including digital photography, where you use a binary value with a specified number of bits to represent some data. That binary value then has upper and lower limits implied by the number of bits and the way they are used to encode values.
In this context it looks like the code is generating noise to add to an image. The expression that generates the noise is not quoted but the comments suggest a Poisson distribution, which is a mathematical function which could produce outputs exceeding the dynamic range of the image. The two flags clipping_below and clipping_above are control flags which allow the user to specify whether those values should be clipped, i.e. constrained to the upper and lower limits of the datatype.


text:
Q: Android builds are supported only on Linux and macOS (React Native Expo) Good morning everyone, I have an application made in Expo, and this week I was going to configure Admob to be able to upload it to the Playstore, but I was surprised by the discontinuity of Admob, requiring a whole new configuration, following the steps below for a simple test in a new blank app I'm not able to create the file to emulate and be able to follow the tests, could you check what I did wrong?
In the "Windows10" terminal:
1 - expo init test
2 - I go to the test folder
3 - expo install expo-dev-client
4 - expo install react-native-google-mobile-ads
Then I put this information in App.js inside Visual Studio code
"react-native-google-mobile-ads":{
"android_app_id": "ca-app-pub-3940256099942544~3347511713",
"ios_app_id": "ca-app-pub-3940256099942544~1458002511"
}
test-only ids
In the terminal again
5 - npm install -g eas-cli
6 - easy login
7 - eas build:configure ( Here I select Android )
In this step, a new file appears in the folder, the eas.json, doing the 2 ways below it gives an error:
"android":{
"simulator":true
}
and even without adding anything
at the terminal
8 - eas build -p android --profile development --local
Now that there is a problem, it keeps giving the error below
"Android builds are supported only on Linux and macOS",
I use Windows 10, can I solve this somehow?
this is the video of the developer who did the above methods, in her case he did it via MAC, but I only have Windows 10, can I solve this somehow? what is my best option?
Thank you all in advance and sorry for the English, I'm Brazilian and I'm using Google translator.

A: This helped me!

*

*I installed Ubuntu on wsl on my windows machine

*Installed node and npm

*Used ubuntu to create the build file

A: yes, just open Ubuntu in your project directory and execute step
EAS build -p android --profile development --local

then drop the generated APK file on your emulator or android and then switch back to PowerShell and execute step 9

A: There is another way to solve this, but this might be a longer route
eas build --profile development --platform android
This uses the EAS server to build the APK. So you still have to download it and install on your device


text:
Q: What math objects were named long after their discovery? I once mentioned F024A or GP(12,5) really needed a name, and David Eppstein later came up with the perfect name for it, the Nauru graph.
When a puzzle based on 30-60-90 triangles became popular, I called the pieces polydrafters after the drafter's triangle, and the name stuck.
Heegner numbers 1, 2, 3, 7, 11, 19, 43, 67, 163 were named years after Heegner's death because his proof was weird and disregarded, but it turned out to be correct. And maybe because too many things were named after Gauss.
In 1979, Howard Garns developed the puzzle Number Place, and the term was trademarked in English countries.  It became popular in Japan, where a more Japanese word was trademarked.  It then became popular worldwide as Sudoku, because that was the name not trademarked.  (In Japan, it's known as Number Place).
Due to $\mathbb{Q}(\sqrt{-1})$ being Gaussian integers, $\mathbb{Q}(\sqrt{-3})$ being Eisenstein integers and  $\mathbb{Q}(\sqrt{-7})$ being  Kleinian integers, I've made an attempt at naming $\mathbb{Q}(\sqrt{-2})$  the Hippasus integers, because Hippasus was famously killed for proving the immeasuarability of $\sqrt{2}$.  Whether that naming attempt will be successful remains to be seen.
What are other cases where things got good names long after the fact?

A: The term Euclidean algorithm does not seem to have been used before the 20th century, according to this site. In antiquity it was just called reciprocal subtraction.


text:
Q: Redirect to HTTPS and Apex Domain with Nginx location Configuration I would like to force HTTPS and the apex domain (e.g. https://example.com) in my application through nginx configuration using location blocks. I currently have the following nginx_app.conf file (which works with both the apex and the www subdomain, and both http and https):
location / {
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|config)\.php(/|$) {
    # fastcgi_pass directives go here...
}

To force the apex domain and https, I tried using if-statements as follows, checking for the $scheme and $host variables, but I get an error that the page is not redirecting properly. I also added an HSTS directive.
location / {
    if ($scheme = http) {
        rewrite ^/(.*) https://$host/$1 permanent;
    }
    if ($host = www.example.com) {
        rewrite ^/(.*) https://example.com/$1 permanent;
    }
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|config)\.php(/|$) {
    # fastcgi_pass directives go here...
    add_header Strict-Transport-Security "max-age=86400";
}

What is the proper way to force http and the apex domain with nginx configuration? As an aside, I'm using heroku (with DNSimple) to deploy my app so I would like both the following domains to work: https://example.herokuapp.com and https://example.com.
UPDATE:
I tried moving the if-statements outside the location block into the default server block (click here), and change the rewrites for returns as follows, but it still does not work. I still get "The page isn't redirecting properly" when requesting http, and "Unable to connect error" when requesting the www subdomain.
if ($scheme = http) {
    return 301 https://$host$request_uri;
}
if ($host = www.example.com) {
    return 301 https://example.com$request_uri;
}

location / {
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|config)\.php(/|$) {
    # fastcgi_pass directives go here...
    add_header Strict-Transport-Security "max-age=86400";
}

A: 1) The problem here is probably the Heroku load balancer. When the request of a visit comes in your app the request is HTTP again. It is just the internal routing. You can not test against $scheme. But Heroku set a $http_x_forwarded_proto header on those requests.
if ($http_x_forwarded_proto != "https") {
  return 301 https://$host$request_uri;
}

Source: https://discussion.heroku.com/t/force-ssl-and-no-www-with-nginx-configuration/856

2a) For directing to no-www you can use this:
server {
  listen <%= ENV["PORT"] %>;
  server_name "~^www\.(.*)$";
  return 301 https://$1$request_uri;
}

For testing you should use 302 instead of 301 because the browser will cache 301 redirects.
This one will redirect you to https as well. But only from the www subdomain, so you have to keep the above $http_x_forwarded_proto redirect.
2b) Another option is to use a server block with the www subdomain and redirect it to the non-www domain, like this:
server {
  listen <%= ENV["PORT"] %>;
  server_name www.example.com;

  location / {
    return 301 https://example.com$request_uri;
  }
}

server {
  listen <%= ENV["PORT"] %>;
  server_name example.com;

  location / {
    try_files $uri $uri/ /index.html =404;
  }
}

The <%= ENV["PORT"] %> code comes from a buildpack. On Heroku you can't listen to port 80.

A: The best way is to do a 301 redirect.
server {
    listen         80;
    return 301 https://$host$request_uri;
}


text:
Q: Adding credentials to AmazonKinesisAsyncClientBuilder Elsewhere in StackOverflow (link), access to AWS S3 is done like this:
AmazonS3 amazonS3 = AmazonS3Client.builder()
    .withRegion("us-east-1")
    .withCredentials(new AWSStaticCredentialsProvider(creds))
    .build();

I'd like to use this pattern for AmazonKinesisAsyncClientBuilder, but there aren't any methods to set the region, or credentials.
i.e. this cannot compile:
  AmazonKinesisAsyncClientBuilder
    .withRegion("eu-west-1")
    .withCredentials(new AWSStaticCredentialsProvider(creds))
    .build();

I'm bringing in creds from a custom file (a normal thing in AWS); does AmazonKinesisAsyncClientBuilder only work with the defaults?
Using AWS SDK for Java 2.5.1
Planning to read Kinesis via AlpakkaKinesis, but that may not be relevant.

A: Need to do it with
AmazonKinesisAsyncClientBuilder.standard()
  .withRegion("eu-west-1")
  .withCredentials(...)
  .build()

Unlike S3, there does not seem to be AmazonKinesisAsync.builder() so the cases vary slightly.


text:
Q: Create Highchart graph from specific CSV file I'm new to using php/jscript/etc. At the moment I'm working at meteo station, using Arduino to save data in CSV file. It looks like:

1,25.65
2,25.44
3,24.81
4,25.55
6,24.56

I've read how-to use CSV file in Highchart where header line containes categories the rest of the lines contain data with their name in the first position.
But I'd like to have categories named in script (X-time, Y-temperature). And first position is time and rest is data.
I'm trying scripts from this site, but it's all blank after I put them into my htm :(

A: Try this out:
var series = {
    data: []
};

$(document).ready(function() {
    var options = {
        chart: { renderTo: 'container', defaultSeriesType: 'line' },
        title: { text: 'Chart Example' },
        xAxis: { title: { text: 'Time' }, categories: []    },
        yAxis: { title: { text: 'Temperature'    } },
        series: []
    };
    $.get('data.csv', function(data) {
        var lines = data.split('\n');
        $.each(lines, function(lineNo, line) {
            var items = line.split(',');

            $.each (items, function(itemNo, item) {
                if (itemNo == 0) {
                    options.xAxis.categories.push(item);
                }
                else {
                    series.data.push(parseFloat(item));
                }
            });
        });
        options.series.push(series);
        var chart = new Highcharts.Chart(options);
    });
});

Where 'container' is a div, and data.csv is the file containing your data (in the same directory as your HTML file)


text:
Q: Rails db:seed doesn't create records when foreign key is a large number I'm trying to populate a mysql2 database and not all records are being added into the database.
This is my schema
create_table "accounts", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
  t.string "name_es"
  t.string "name_en"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "dbid"

create_table "company_account_categories", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
  t.integer "company_type"
  t.integer "account_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["account_id"], name: "index_company_account_categories_on_account_id"

add_foreign_key "company_account_categories", "accounts"

In my seeds I have CompanyAccountCategory records with account_id between 101 and 177 which all get wrote into the DB, while records with account_id 22077 or greater are not.
Example:
CompanyAccountCategory.find_or_create_by(account_id: 176, company_type: 4)
CompanyAccountCategory.find_or_create_by(account_id: 22133, company_type: 1)


text:
Q: Why does this SQLite UPDATE statement write changes to all records in the table? This query returns 40319 records:
SELECT artist,
       title,
       composer AS alib_composer,
       master.composer AS master_composer
  FROM alib
       INNER JOIN
       master ON hex(alib.__path) = hex(master.__path) AND
                 alib.l_title = lower(master.title) AND
                 alib.composer != master.composer AND
                 length(alib.composer) != length(master.composer) AND
                 master.composer LIKE "% %" AND
                 alib.composer NOT LIKE "% %";

Translating above into the following UPDATE query results in all records in alib being updated.  Could someone help me understand why this is the case?
UPDATE alib
   SET composer = (
           SELECT composer
             FROM master
            WHERE hex(alib.__path) = hex(master.__path) AND
                  alib.l_title = lower(master.title) AND
                  alib.composer != master.composer AND
                  length(alib.composer) != length(master.composer) AND
                  master.composer LIKE "% %" AND
                  alib.composer NOT LIKE "% %"
       );

I suspect I know why, but turning the update into something like this:
UPDATE alib
   SET composer = master.composer
 WHERE hex(alib.__path) = hex(master.__path) AND
        alib.l_title = lower(master.title) AND
        alib.composer != master.composer AND
        length(alib.composer) != length(master.composer) AND
        master.composer LIKE "% %" AND
        alib.composer NOT LIKE "% %";

causes SQLite to complain:
Error while executing SQL query on database 'x': no such column: master.composer

A: Because there is no WHERE clause on the outer/main UPDATE SQL i.e. it is basiclly
UPDATE alib SET composer = the_result_of_the_subquery;

*

*i.e. UPDATE every row.

You want a WHERE clause to say which rows to update along the lines of :-
UPDATE alib SET composer = the_result_of_the_subquery WHERE ??????;

Or to use your code :-
UPDATE alib
    SET composer = (
       SELECT composer
         FROM master
        WHERE hex(alib.__path) = hex(master.__path) AND
              alib.l_title = lower(master.title) AND
              alib.composer != master.composer AND
              length(alib.composer) != length(master.composer) AND
              master.composer LIKE "% %" AND
              alib.composer NOT LIKE "% %"
   )
WHERE the_expression_to_restrict_which_rows_are_updated
;

This hasn't been fully tested but this may be solution you are looking for :-
WITH cte AS
    (
        SELECT
            master.composer AS master_composer,
            alib.rowid AS arowid
        FROM alib
            INNER JOIN
                master ON hex(alib.__path) = hex(master.__path)
                    AND alib.l_title = lower(master.title)
                    AND alib.composer != master.composer
                    AND length(alib.composer) != length(master.composer)
                    AND master.composer LIKE '% %'
                    AND alib.composer NOT LIKE '% %'
    )
UPDATE alib
SET composer =
    (
        SELECT cte.master_composer FROM cte WHERE cte.arowid = alib.rowid
    )
WHERE alib.rowid IN (SELECT arowid FROM cte);

*

*this uses a Common Table Expresssion(CTE) (temporay table that exists just for the query).

*It utlises the rowid (a hidden column that every table has other than WITHOUT ROWID tables).

*That is the CTE is based upon your original query that extracts the rows from alib that need to be updated. It only needs the composer from the master table and the rowid of the alib table for the update.

*The UPDATE sets the composer to the value of the master_composer column of the respective row from the CTE according to the rowid of the row being updated.

*The UPDATEs are only applied to rows that have a matching row in the CTE.

Testing (limited)
The following SQL was used for testing :-
DROP TABLE IF EXISTS alib;
DROP TABLE IF EXISTS master;
CREATE TABLE IF NOT EXISTS alib (__path,l_title,composer);
CREATE TABLE IF NOT EXISTS master (__path,title,artist,composer);

INSERT INTO alib VALUES
    ('path1','this','bert'),
    ('path2','something else','Joe'),
    ('path2','something else','Joe'), -- duplicate likely irrelevant but still updated
    ('path2','something else','Joe Someone'), -- already has space in composer skipped
    ('path100','an so on','x') -- no equivalent in master
;
INSERT INTO master VALUES
    ('path1','this','fred','bert'), -- ignored as no space
    ('path1','this','fred bloggs','Julia smith'),
    ('path2','something else','Alison','Joe Brown')
;

/* DEMO OF EXTRACTED ROWS */
WITH cte AS
    (
        SELECT
            master.composer AS master_composer,
            alib.rowid AS arowid
        FROM alib
            INNER JOIN
                master ON hex(alib.__path) = hex(master.__path)
                    AND alib.l_title = lower(master.title)
                    AND alib.composer != master.composer
                    AND length(alib.composer) != length(master.composer)
                    AND master.composer LIKE '% %'
                    AND alib.composer NOT LIKE '% %'
    )
SELECT * FROM cte;

WITH cte AS
    (
        SELECT
            master.composer AS master_composer,
            alib.rowid AS arowid
        FROM alib
            INNER JOIN
                master ON hex(alib.__path) = hex(master.__path)
                    AND alib.l_title = lower(master.title)
                    AND alib.composer != master.composer
                    AND length(alib.composer) != length(master.composer)
                    AND master.composer LIKE '% %'
                    AND alib.composer NOT LIKE '% %'
    )
UPDATE alib
SET composer =
    (
        SELECT cte.master_composer FROM cte WHERE cte.arowid = alib.rowid
    )
WHERE alib.rowid IN (SELECT arowid FROM cte);

SELECT * FROM alib;
DROP TABLE IF EXISTS alib;
DROP TABLE IF EXISTS master;

Testing Results
The extracted data :-

alib table after UPDATES :-


text:
Q: ¿COMO PUEDO VALIDAR UN INPUT PARA QUE SOLO ACEPTE LAS VOCALES? Necesito usar lo mpas básico, for, if,else,arrays.

A: lo puedes hacer directamente con html5 con el atributo partenr
esto se vería así

<form name="formulario" method="post">

  <input type="text" name="nombre" placeholder="Vocales"
         required pattern="[AEIOUaeiou]{5,40}"
         title="Letras. Tamaño mínimo: 5. Tamaño máximo: 40">
</form>

Deberías de mostrar el código que ya tienes, para orientarte mejor. Dado que si lo piensas hacer con estructuras de control es más complejo. Lo que necesitas se resume a evaluar una expresión regular.
aquí te va una idea extra

function evelua_texto(e){
  for(let a in e.value.split('')){
     switch (e.value.split('')[a]) {
        case 'a':
            correcto();
            break;
        case 'e':
            correcto();
            break;
        case 'i':
            correcto();
            break;
        case '0':
            correcto();
            break;
        case 'u':
            correcto();
            break;
        default:
        error();
            break;
    }
  }
}

function error(){
  var el = document.getElementById('error');
  el.innerText ="Este texto incluye valores no permitidos";
}

function correcto(){
  var el = document.getElementById('error');
  el.innerText = "correcto";
}
<input id="input" type="text" placeholder="volcales" onKeyUp="evelua_texto(this)">

<div id="error" />

Como sea espero haberte ayudado.


text:
Q: DataInterval: как определить наступила ли дата или нет? Имеется string вида '2016-07-25 18:14:00' Как определить наступила ли дата или нет?

A: Можно поступить следующим образом
<?php
$date = new DateTime('2016-07-25 18:14:00');
$now = new DateTime();
if($date < $now) echo 'Дата наступила';
echo 'Дата не наступила';

A: можно воспользоваться функцией strtotimeкоторая приведет вашу строку в метку времени Unix, и дальше сравнить полученный результат с результатом полученным от функции time()

A: $now = new DateTime();
$diff = $now->diff('дата');

if($diff->invert)
 //прошедшее время
else
 //будущее время


text:
Q: Nested rows with bootstrap grid Necesito crear una rejilla, como lo muestra la siguiente imagen, estoy utilizando bootstrap 3
Ejemplo:
Gracias!!

A: Para esto puedes usar el siguiente código:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      Contenido 1

              Contenido 2

              <button class="btn btn-primary">Btn ok</button>

              <button class="btn btn-default">Btn cancel</button>


text:
Q: Find value of $k$ for a function to be continous The given function
and the domain of $g(x)$ is $(0 ,\pi/2)$.
where $[\ \ ]$ denotes the greatest integer function.
Find the value of $k$, if possible, so that $g(x)$ is continuous at $x =\pi/4$.
I thought about it alot , but could not get any start .
Please help me in this

A: First we will simplify $$f(x) = \sum^{n}_{r=1}\tan \left(\frac{x}{2^r}\right)\cdot \sec \left(\frac{x}{2^{r-1}}\right)$$
So $$f(x) = \sum^{n}_{r=1}\frac{\sin \left(\frac{x}{2^r}\right)}{\cos \left(\frac{x}{2^r}\right)\cdot \cos\left(\frac{x}{2^{r-1}}\right)} =\sum^{n}_{r=1} \frac{\sin \left(\frac{x}{2^{r-1}}-\frac{x}{2^{r}}\right)}{\cos \left(\frac{x}{2^r}\right)\cdot \cos\left(\frac{x}{2^{r-1}}\right)}$$
So $$f(x) = \sum^{n}_{r=1}\left\{\tan \left(\frac{x}{2^{r-1}}\right)-\tan \left(\frac{x}{2^r}\right)\right\}$$
Now expanding summation, We get $$f(x) = \tan x-\tan \left(\frac{x}{2^{n}}\right)$$
So $$f(x)+\tan \left(\frac{x}{2^r}\right) = \tan x$$
So $$g(x) = \lim_{n\rightarrow \infty} \frac{\ln (\tan x)-(\tan x)^n\cdot \lfloor \sin \left(\tan \frac{x}{2}\right)\rfloor}{1+(\tan x)^n}$$
Now Given $\displaystyle 0<x<\frac{\pi}{2}\Rightarrow  0<\frac{x}{2}<\frac{\pi}{4}\Rightarrow 0<\tan \frac{x}{2}<1\Rightarrow 0<\sin \tan \frac{x}{2}<\sin (1)<\sin \frac{\pi}{2}$
So we get  $\displaystyle \lfloor \sin \tan \frac{x}{2} \rfloor = 1$
For continuity at $\displaystyle x = \frac{\pi}{4}$
$$k = \lim_{x\rightarrow \frac{\pi}{4}}\lim_{n\rightarrow \infty} \frac{\ln (\tan x)-(\tan x)^n  }{1+(\tan x)^n}$$


text:
Q: Difference between EventLog.WriteEntry and EventLog.WriteEvent methods I tried using WriteEntry and WriteEvent methods of EventLog class.
EventLog.WriteEntry("Saravanan", "Application logs an entry",
                     EventLogEntryType.Information, 2, 3);
EventLog.WriteEvent("Saravanan",  new EventInstance(2, 3),
                                 "Application logs an event");

Both output the same result.
Is there any difference in usage of these methods?
If there are only minor difference, why was it not done through a overload of either WriteEvent() or WriteEntry() methods, instead of introducing a new method?

A: EventLog.WriteEntry is a "quick and dirty" way to write to the event log where you can write a string. EventLog.WriteEvent enables you to take full advantage of the native Win32 API. However, to do that you are supposed to create a localized message file you then compile using the message compiler (mc.exe). Each event can contain substitution strings and can be localized to match the locale on the computer.
To avoid this extra step of creating a message file the .Net wrapper for the event log API use messages that simply inserts the strings supplied as arguments. These message are used by EventLog.WriteEntry and are stored as embedded resources in EventLogMessages.dll in the .Net folder.
Normally using EventLog.WriteEntry is adequate, but if you need to localize your messages or want to maintain them outside your source code you should create a message file and use EventLog.WriteEvent.


text:
Q: Magic trick based on deep mathematics I am interested in magic tricks whose explanation requires deep mathematics. The trick should be one that would actually appeal to a layman. An example is the following: the magician asks Alice to choose two integers between 1 and 50 and add them. Then add the largest two of the three integers at hand. Then add the largest two again. Repeat this around ten times. Alice tells the magician her final number $n$. The magician then tells Alice the next number. This is done by computing $(1.61803398\cdots) n$ and rounding to the nearest integer. The explanation is beyond the comprehension of a random mathematical layperson, but for a mathematician it is not very deep. Can anyone do better?

A: I gave a talk about card shuffling to a general audience recently and wanted to memorise a "random-looking" deck so as to motivate a correct definition of what it means for a deck to be random. Most magicians actually use memory tricks to learn off the deck but I thought it would be much cleverer to order the cards in the obvious way, and then find a recursive sequence of length 52 containing all of 1 to 52. In the end, caught for time I settled on using the Collatz recursive relation with seed 18 --- this allowed me to name off 21 distinct cards effortlessly and when I held up the deck prior to the demonstration, the audience voted that the deck was random. Can anyone think of a suitable recursive sequence with the desired property? We can either take a random-looking order and a "regular" recursive sequence but I think it would be much better to find an easy to compute recursive sequence that "looks random" when using a more canonical order simply because if we can remember a "random looking order" we're pretty much going to have to remember the whole deck --- the problem I'm exactly trying to avoid.
PS: I did one of the simpler Diaconis tricks. A deck is riffle shuffled three times, the top card shown to the audience, inserted into the deck, and after laying the cards out on the table the top card can be easily recovered by looking at the descents. The key is that the order of the deck is known beforehand --- a simple demonstration that three shuffles does not suffice to mix up a deck of cards (with respect to variation distance).

A: Here is a simple trick based on group theory.  Ask a person to choose four numbers from 1 to 9 and write them in a row on a piece of paper.  Pause for a moment and then write a number on a piece of paper without letting the other person see what it is.  Turn the paper over and place it on the table.
Now ask the person to choose two of the numbers from the list and put a line though them.  Ask the person to compute a*b + a + b and put it in the list to replace the two chosen numbers.
Continue to do this until there is only one remaining number.  Turn over the paper and show that the numbers match.
The simplest way of explaining this is to show that a * b + a + b is isomorphic to multiplication using the transform T(x) = x + 1.  (a*b + a + b) + 1 = (a + 1)(b + 1).  If we denote the operation a * b + a + b as a & b, this means that a & b is commuative and associative, just as multiplication is.  For any list of numbers ai,  the final number can be computed as the (a1 + 1)(a2 + 1)...(an + 1) - 1.

A: Ask someone to lay out the 52 cards in a deck, face up, in 4 rows of 13 cards each, in any order the person wants. Then you can always pick 13 cards, one from each column, in such a way as to get exactly one card of each denomination (that is, one ace, one deuce, ..., one king).
As a trick, it's not up there with sawing a woman in half, but its explanation does require Hall's Marriage Theorem.

A: Two persons, A and B, perform this trick. The public (or one from the public) chooses two natural numbers and give A the sum and B the product. A and B will ask each other, alternatively, the only single question "Do you know the numbers?" answering only yes or no until both find the numbers. There is a strategy such that for any input and only doing this, A and B will manage to find the original numbers.
I have never seen magicians actually performing this, but is perfectly doable.
This was a problem in the shortlist of the proposed problem for some international mathematical olympiad. Unfortunately I don't remember which. If someone remembers or finds it. Tell us please. i would also like to know.

A: Here's another Fibonacci trick, from Benjamin & Quinn's "Proofs that really count".

The magician hands a volunteer a sheet of paper with a table whose rows are numbered from one to ten, plus a final row for the total. She asks him to fill in the first two rows with his favorite two positive integers. She then asks him to fill in row three with the sum of the first two rows, row four with the sum of row two and row three, etcetera... She then hands him a calculator and asks him to add up all ten numbers together. Before he's able to finish that, the magician has a quick look at the sheet of paper and announces the total. The magician then asks the volunteer to divide row 10 by row 9, and cut up the answer to the second decimal digit. The volunteer performs the division and says: 1.61. And the magician: "Now turn over the paper and look what I've written". The paper says: "I predict the number 1.61".

The first part of the trick uses the following well-known Fibonacci identity:
$$\sum_{i=1}^nF_i=F_{n+2}-1$$
Indeed, call $x$ the number in row 1 and $y$ the number in row 2. Then for $n \geq 3$, the number in row $n$ is $F_{n-2} x+F_{n-1} y$, where $F_n$ is the $n$-th Fibonacci number. So the number in row 7 is $F_5 x + F_6 y=5x+8y$ and the total is $$x+y+\sum_{i=3}^{10} (F_{i-2} x+F_{i-1} y)= F_{10} x + F_{11} y=55x+88y$$ by the Fibonacci identity mentioned at the beginning. Therefore all the magician has to do to find the total is multiply row 7 by the number 11.
The second part of the trick uses an inequality for the freshman sum ;-) of two fractions. That is, given positive fractions $\frac{a}{b}$ and $\frac{c}{d}$ such that $\frac{a}{b}<\frac{c}{d}$ we have:
$$\frac{a}{b} < \frac{a+c}{b+d} < \frac{c}{d}$$
Just note that the number in row 9 is $13x+21y$ while the number in row 10 is $21x+34y$. Hence:
$$
1.615 \dots =\frac{21x}{13x} < \frac{21x+34y}{13x+21y} < \frac{34y}{21y}=1.619 \dots
$$

A: This was fascinating for me. Somehow the man takes a bagel and with one cut arrives with two pieces that are interlocked. Whether this qualifies as "magic" I dunno (it's hard to say once the trick's been explained), but it sure seems like it to me.
It doesn't hurt that I love bagels, and have the opportunity to perform this with friends/family/non-math people and can teach a little about problems/topology/counter-intuitive facts about the universe.

A: Here's an example of a magic trick that works with high probability, based on a careful analysis of the riffle shuffle, in which an audience member performs a number of riffle shuffles and then moves a single card, and the magician guesses which card has been moved.

A: Not so much a magic trick as a math trick, in that I can prove it works in theory but I have never tried it in practice.
Take a very long one-dimensional frictionless billiard table, with a wall at one end.  Away from the wall, place a billiard ball with mass $10^{2n}$ for $n$ positive.  Between that ball and the wall, place another billiard ball with mass $1$.  Then start the heavy ball rolling slowly towards the light one.  Of course, they bounce, setting the light one traveling quickly towards the wall, which it bounces off, and then it hits the heavy ball, etc., until all the momentum from the heavy ball has been transferred and it starts rolling away.
Assume that all collisions are perfectly elastic.  Then at the end of the day, there will be finitely many collisions.  Indeed, the number of collisions will calculate the digits of $\pi$, in the sense that there will be $\lfloor \pi \times 10^n \rfloor$ collisions.
I prefer this method of calculating $\pi$ much better than the probabilistic one.

A: So two points of note.
I did not read all the posts above in detail but did do a search for the Faro Shuffle and got no results... So:
This is a shuffle where all the cards interweave absolutely perfectly (so a perfect riffle shuffle). There's quite a lot of maths behind this. For instance, 8 shuffles takes you back to the order you started shuffling the cards in. Martin Gardner talked about this a bit in at least one of his SA columns. The problem with the faro shuffle is it takes a long long time to learn... personally well over a year, and that was with the benefit of having been a practicing amateur magician for along time. Still if interested the book to look for is The Collected Works of Alex Elmsley, this really lays the foundations for mathematical faro work...
Another trick I came across whilst working towards an Ergodic Theory exam uses the Birkhoff Ergodic Theorem at its core. You can read about it in these notes: http://www.maths.manchester.ac.uk/~cwalkden/ergodic-theory/lecture22.pdf
Owen.

A: Peter Suber writes:
By the way, the single best knot trick I've ever found is at pp. 98-99 of Louis Kauffman's On Knots, a mathematical treatise listed below with the books on knot theory. I'm sure you've seen the trick in which someone ties an overhand knot by crossing their arms before picking up the cord, and then uncrossing them. Kauffman shows you how to do the same trick without crossing your arms first. The version of this trick in Ashley #2576 and Budworth 1977 [p. 151] is not nearly as good.
Work out how it is possible for yourselves! A link to the book is here.
[Edit: This magic trick does not rely on mathematics -- instead it violates an important mathematical fact, that the trefoil is not unknotted! The Chinese rings have a similar feel, but the mathematics violated (linking number) is less deep.]

A:
Place $K$ faced-down cards on a table, blindfold yourself and ask him/her for a number $1 < n < K$. Allow him/her to flip $n$ random cards up. Cover the cards with an opaque box that has two holes for you to put your hands in and claim that you can split the cards into 2 stacks, each with same number of faced-up cards.

Based on a well known logic puzzle: http://usna.edu/Users/physics/mungan/_files/documents/Scholarship/CoinPuzzle.pdf
Modified the process to make it harder for audience to figure out what you did and used cards so that they will not think that you did it by differentiating the surface of the coins.

A: A recent episode of Penn and Teller's Fool Us had a trick by Hans Petter Secker which exploits the parity of a permutation in a lovely way.  It may be useful the next time one has to teach the sign of a permutation!
Brief description of the trick in the video:  The magician has sent a box over.  Penn picks up a Rock from the box; Teller then picks Scissors from the box; and Alysson gets the remaining crumpled sheet of paper.  The magician (on video) says that he will predict what they'll do (in the context of the Rock-Paper-Scissors game).  He writes down a prediction, and invites Alysson to pick any two of them and swap their objects. The magician reveals his correct prediction.  Next he writes down two predictions, and asks Teller to perform a swap, and then Penn to perform a swap (I might be forgetting who selects the swaps, but two swaps are made).  Again the magician reveals his correct predictions.  Finally he gets them to make three swaps.  This time he has not written down any predictions, but when the crumpled paper is smoothed out, there are three correct predictions written on it. Enjoy!
https://www.youtube.com/watch?app=desktop&v=hf7Sy7FPal0

A: Five unrelated items:
Mobius strip
One of the best mathematical tricks is what happens when you cut a Mobius strip in the middle. (Look here) (And what happens when you cut it again, and when you cut it not in the middle.) This is truly mind boggling and magicians use it in their acts. And it reflects deep mathematics.
Diaconis mind reading trick
I also heard from Mark Gorseky this description of a mathematical based card game
"Mark described a card trick of Diaconis where he takes a deck of cards, gives it to a person at the end of the room, lets this person "cut" the deck and replace the two parts, then asks many other people do the same and then asks people to take one card each from the deck. Next Diaconis is trying to read the mind of the five people with the last cards by asking them to concentrate on the cards they have. To help him a little against noise coming from other minds he asks those with black cards to step forward. Then he guesses the cards each of the five people have.
Mark said that Diaconis likes to perform this magic with a crowd of magician since it violates the basic rule: "never let the cards out of your control". This trick is performed (with a reduced deck of 32 cards) based on a simple linear feedback shift register. Since all the operations of cuting and pasting amount to cyclic permutations, the 5 red/black bits are enough to tell the cylic shift and no genuine mind reading is required."
I think there is a paper by Goresky and Klapper about a version of this magic and relations to shift registers.
The Link Illusion
I heard a wonderful magic from Nahva De Shalit. You tie a string between the two hands of
two people and link the two strings. The task is to get unlinked.
This ties with what I heard from Eric Demaine about the main principle behined many puzzles (Some of which he manufectured with his father whan he was six!)
Symmetry Illusion
Sometimes things are not as symmetric as they may look.
commutators-based magic
(I heard this from Eric Demaine and from Shahar Mozes.) If we hang a picture (or boxing gloves) with one nail, once the nail falls so does the picture. If we use two nails then ordinarily if one nails falls the picture can still hangs there. Mathematics can come for the rescue for the following important task: use five nails so that if any one nail falls so does the picture.

A: I saw this trick demonstrated at a math camp once. When it works, it is extremely impressive to non-mathematicians and mathematicians alike.
Have a volunteer shuffle a deck of cards, select a card, show it to the audience, and shuffle it back into the deck. Take the deck from him, and fling all of the cards into the air. Grab one as it falls, and ask the volunteer if it is his card.
1 in 52 times (this is the deep mathematics part), the card you grab will be the card the volunteer selected. Even most statisticians should be amazed at this feat. Just make sure you never perform this trick twice to the same audience.

A: I forgot the historical name for this and I'm pretty sure this is classical and well-known.
Consider a circular disk and remove an interior circular region, not necessarily concentric. In this annulus we play the following game. Start at any point $p_{1}$ of the outer boundary and draw a line through this point which is tangent to the inner circle. This line intersects the outer circle at another point $p_2$. Now repeat the same procedure with $p_2$ and get $p_3$. Iterating this procedure ad infinitum we either conclude that these sequence of points are periodic or not. What's true is that the periodicity or lack of it is independent of the starting point $p_1$.
I believe there is a proof involving Lefschetz fixed point theorem involving the torus but any details on this and the history of this is more than welcome.

A: Magician: "Here is a deck of 27 cards. Select one, memorize it, put it back and shuffle at libitum. Now name a number between 1 and 27 inclusive (=: N)." Then the magician deals the cards face up into three heaps. You have to tell him in which heap the selected card lies, and he quickly ramasses the three heaps. This is done three times, then he hands you the deck, and you have to count N cards from its back. The N'th card is flipped over, and it turns out to be the card you have originally selected.

A: This is a trick that I designed years ago and I have used it in many different occasions for amusement only or educational purpose or both. It is indeed the finial difference method to find a polynomial. Ask the person to write down a polynomial without you knowing the polynomial  and even the degree of the polynomial. To keep your life easy, it would be better to keep the degree less than or equal 3. (It wouldn't be hard to let a layman know what a polynomial is just by giving two or three examples). Then you ask for some information that is essentially the value of the polynomial for 0, 1, 2, 3. As soon as you take one of the value you should calculate the difference. And in a few seconds after taking the last information, you announce not only the degree of the polynomial but also the exact polynomial.
Note 1: Finding the degree is a very important part of this trick since it convinces more knowlegable persons that you are not just solving a simultaneous equation quickly.
Note 2: I used this trick in my Calculus classes to give this seemingly paradoxical idea that "if you don't know what the function is, try to figure out how it changes."
Note 3: Of course, one can use it in many different classes for different purposes.
Note 4: I've just search the internet to see if Martin Gardner ever introduced this trick. Damn it! The answer was yes, here: "The calculus of finite differences". However, I still love to keep the credit of telling the degree for my self :)

A: My favourite example, the rope and two carabiner trick
http://blogs.scientificamerican.com/guest-blog/amazing-rope-trick/
I also offer up my variation of the Dirac belt trick
https://m.youtube.com/watch?v=UtdljdoFAwg

A: Here is a trick much in the spirit of the original number-adding example; moreover I'm sure Richard will appreciate the type of "deep mathematics" involved.
On a rectangular board of a given size $m\times n$, Alice places (in absence of the magician) the numbers $1$ to $mn$ (written on cards) in such a way that rows and columns are increasing but otherwise at random (in math term she chooses a random rectangular standard Young tableau). She also chooses one of the numbers say $k$ and records its place on the board. Now the she removes the number $1$ at the top left and fills the empty square by a "jeu de taquin" sequence of moves (each time the empty square is filled from the right or from below, choosing the smaller candidate to keep rows and columns increasing, and until no candidates are left). This is repeated for the number $2$ (now at the top left) and so forth until $k-1$ is gone and $k$ is at the top left. Now enters the magician, looks at the board briefly, and then points out the original position of $k$ that Alice had recorded. For maximum surprise $k$ should be chosen away from the extremities of the range, and certainly not $1$ or $mn$ whose original positions are obvious.
All the magician needs to do is mentally determine the path the next slide (removing $k$) would take, and apply a central symmetry with respect to the center of the rectangle to the final square of that path.
In fact, the magician could in principle locate the original squares of all remaining numbers (but probably not mentally), simply by continuing to apply jeu de taquin slides. The fact that the tableau shown to the magician determines the original positions of all remaining numbers can be understood from the relatively well known properties of invertibility and confluence of jeu de taquin: one could slide back all remaining numbers to the bottom right corner, choosing the slides in an arbitrary order. However that would be virtually impossible to do mentally. The fact that the described simple method works is based on the less known fact that the Schútzenberger dual of any rectangular tableau can be obtained by negating the entries and applying central symmetry (see the final page of my contribution to the Foata Festschrift).

A: Persi Diaconis and Ron Graham just published Magical Mathematics. The book contains a plethora of magic tricks rooted in deep mathematics.

A: The following trick uses some relatively deep mathematics, namely cluster algebras.  It will probably impress (some) mathematicians, but not very many laypeople.
Draw a triangular grid and place 1s in some two rows, like the following except you may vary the distance between the 1s:
1   1   1   1   1   1   1
  .   .   .   .   .   .
.   .   .   .   .   .   .
  .   .   .   .   .   .
.   .   .   .   .   .   .
  .   .   .   .   .   .
1   1   1   1   1   1   1

Now choose some path from the top row of 1s to the bottom row and fill it in with 1s also, like so:
1   1   1   1   1   1   1
  1   .   .   .   .   .
.   1   .   .   .   .   .
  1   .   .   .   .   .
.   1   .   .   .   .   .
  .   1   .   .   .   .
1   1   1   1   1   1   1

Finally, fill in all of the entries of the grid with a number such that for every 2 by 2 "subsquare"
  b
a   d
  c

the condition $ad-bc=1$ is satisfied, or equivalently, that $d=\frac{bc+1}{a}$.  You can easily do this locally, filling in one forced entry after another.  For example, one might get the following:
1   1   1   1   1   1   1
  1   2   3   2   2   1
.   1   5   5   3   1   .
  1   2   8   7   1   .
.   1   3   11  2   1   .
  .   1   4   3   1   .
1   1   1   1   1   1   1

The "trick" is that every entry is an integer, and that the pattern of 1s quickly repeats, except upside-down.  If you were to continue to the right (and left), then you would have an infinite repeating pattern.
This should seem at least a bit surprising at first because you sometimes divide some fairly large numbers, e.g. $\frac{5\cdot 11+1}{8} = 7$ or $\frac{7\cdot 3+1}{11} = 2$ in the above picture.  Of course, the larger the grid you made initially, the larger the numbers will be, and the more surprising the exact division will be.
Incidentally, if anyone can provide a reference as to why this all works, I'd love to see it.  I managed to prove that all of the entries are integers, and that they're bounded, and so there will eventually be repetition.  However, the repetition distance is actually a simple function of the distance between the two rows of 1, which I can't prove.

A: The Kruskal count.

A: You may ask the person to encode something by RSA, then you decode it (you have the private key)
OR
To divide two 40-digit integers and give you the decimal result to 100 digits, you then use continued fractions to find the original fraction (reduced)
OR
To compute pq and pr where p,q,r are prime, you then find p,q,r by the Euclidean algorithm (no very deep, but it's the best i've got)

A: Here's a couple of well-known simple topology tricks:
Tie ends of a long enough piece of rope to your wrists, while wearing a loosely fitting jacket or sweatshirt. With your arms tied like that, take the jacket off your back and put it back on inside out. It's easier to figure out how to do it than to explain it in words, so I'll skip the explanation. The more risque version is to tie the ankles and do the trick with pants.
The other one I haven't tried, but maybe it can be done at a party if you have a stick and some plasticine around.
http://www.youtube.com/watch?v=S5fPwE7GQOA

A: A variant on  Anton Geraschenko answer above- say you are in a fourth grade school that for some reason let these poor kids use calculators. you ask them to pick for themselves a 3 digit number say abc. Tell them to write it twice in their calculator ,i.e., abcabc and then divide by 77. Then by 13. What did you get? do it again with 143 and then by 7? What did you get. again with...
It teaches them about prime decomposition, about the decimal structure, about consecutive division etc.
I learnt it from Avraham Arcavi.

A: Destination Unknown is a magic trick that makes use of Combinatorics. It really fools people.
See http://themagicwarehouse.com/cgi-bin/findit.pl?x_item=SP2453&keyword=DESTINATION

A: Although one of the answers mentions Kruskal count, I would like to add more about it. Kruskal count not just works in the case of a paragraph as well. If you start from one of the first ten words of a paragraph, go to the word which is away from the previous word by number of words exactly equal to the letters of the previous word, you'll land up on the same word in the end! For more discussion, you can refer this link

A: A late addition: The Fold and One-Cut Theorem.  Any straight-line drawing
on a sheet of paper may be folded flat so that, with one straight scissors cut right through the paper,
exactly the drawing falls out, and nothing else. Houdini's 1922 book Paper Magic includes instructions
on how to cut out a 5-point star with one cut.  Martin Gardner posed the general question in his Scientific American column in 1960.
For the proof, see Chapter 17 of Geometric Folding Algorithms: Linkages, Origami, Polyhedra.
We include instructions for cutting out a turtle, which, in my experience, draws a gasp from the audience. :-)

A: The coffee mug trick
Give a coffee mug (full if you're brave) to someone and ask them to rotate 360 degrees without spilling the (real or imaginary) coffee, so that their hand ends up in the same position.
This is impossible, so you get to smirk while they contort themselves and become more and more baffled (this works better with more than one person since it turns into a kind of "competition")
Finally, take the cup and show that while it's impossible to turn it once (as has been "proven"), it's possible to turn it twice (!) and end up in the same position.
Has to do with the fundamental group of SO(3) being $\mathbb{Z}/2\mathbb{Z}$, and when we require the cup to stay upright we end with a non-trivial loop.

A: Apart from tricks based on numbers, there are topological objects whose properties can seem quite magical, like the Möbius strip or the unknot.
E.g. take a standard page of paper, show that it has two sides (number them with a pen, show that any straight pen path meets a boundary). Next, cut out a long strip from it (not needed of course, but adds to the drama), and ask the audience "and how many sides does this have?". They reply "two". Then you put the the two small ends of the strip together to form a ring and you ask "and now, how many sides?", they still reply "two!". At this point do a little diversion, like putting a pair of scissors on the table saying out loud "I'll use this in a minute".  Now do a half-twist with the strip before putting the small ends together and ask again "for the last time people, how many sides?". They answer "twoo!!", and you say "the magic has worked people, there's only one side!"  (you show that now the pen paths along the long direction never meet a boundary and come back). Most laymen are quite bemused. Now do two half-twists and ask again, some won't dare an answer...

A: If you are not mathematically inclined, this game can drive you crazy.
http://www.transience.com.au/pearl.html

A:
Here is a general trick that you can use to make yourself look like you have an amazing memory.

Start with a finite abelian group $(G,+)$ in which you are comfortable doing arithmetic. Be sure to know the sum $$g^* = \sum_{g \in G} g.$$
Take a set $S$ of $|G|$ physical objects with an easily computable set isomorphism
$$ \varphi : S \longrightarrow G.$$
Allow your audience to remove one random element from $a \in S$ and then shuffle $S$ without telling you what $a$ is. [Shuffling means we need $G$ to be abelian.]
Now inform your audience that you are going to look briefly at each remaining element of $S$ and remember exactly which elements you saw, and determine by process of elimination which element of $S$ was removed.
Now glace through all the remaining elements of $S$ one by one and keep a "running total" to compute
$$ \varphi(a) = g^* - \sum_{s \in S-\{a\}} \varphi(s).$$
Finally apply $\varphi^{-1}$ and obtain $a.$
Note that $\varphi$ is not "canonical" in the sense there are definitely choices to be made. On the other hand in should be "natural" in the sense that you should be very comfortable saying $s = \varphi(s).$

The prototypical example is to take $G$ to be $\Bbb Z / 13 \Bbb Z \times V_4,$ $S$ to be a standard deck of 52 cards, and $\varphi(s)$ to be $( \text{rank}(s) , \text{suit}(s) )$.

A: "The best card trick", an article by Michael Kleber.  Here is the opening paragraph:
"You, my friend, are about to witness
the best card trick there is.
Here, take this ordinary deck of cards,
and draw a hand of five cards from
it. Choose them deliberately or randomly,
whichever you prefer--but do
not show them to me! Show them instead
to my lovely assistant, who will
now give me four of them: the 7 of spades,
then the Q of hearts, the 8 of clubs, the 3 of diamonds.
There is one card left in your hand, known
only to you and my assistant. And the
hidden card, my friend, is the K of spades."

A: Audience asked to choose an integer from 0 to 1000. Ask to give remainder when divided by 7, 11, and 13 respectively.
Magician gives original integer by Chinese Remainder Theorem.
Works because 7×11×13=1001.

A: This trick exploits the thinness of coins.
http://www.howtodotricks.com/easy-coin-magic-trick.html

A: A puzzle based on Hamming codes discussed here: is the following:
A room contains a normal 8×8 chess board together with 64 identical coins, each with one "heads" side and one "tails" side. Two prisoners are at the mercy of a typically eccentric jailer who has decided to play a game with them for their freedom. The rules are the game are as follows.
The jailer will take one of the prisoners (let us call him the "first" prisoner) with him into the aforementioned room, leaving the second prisoner outside. Inside the room the jailer will place exactly one coin on each square of the chess board, choosing to show heads or tails as he sees fit (e.g. randomly). Having done this he will then choose one square of the chess board and declare to the first prisoner that this is the "magic" square. The first prisoner must then turn over exactly one of the coins and exit the room. After the first prisoner has left the room, the second prisoner is admitted. The jailer will ask him to identify the magic square. If he is able to do this, both prisoners will be granted their freedom

A: You can use hamming codes to guess a number with lying allowed. For example, here is a way to guess a number 0-15 with 7 yes-or-no questions, and the person being questioned is allowed to lie once. (The full cards are here).

A: I would like to thank all the contributors on this page.  I have been putting together a new Math-a-Magic show for the 9-12 grade level and have found some fantastic material here.  If I get a decent video of the show I'll be sure to post a link here so you can play the "What concept is behind this trick?" game.
I have modified some of your ideas severely.  For example. Craig Feinstein's suggestion was
a commercial effect that asks the volunteer to pick one of a hundred different cities typed out on ten cards.  The volunteer finds the city's name on two different cards which the magician looks at casually.  You can then instantly tell him the name of the city he has mentally picked.
In my version, I instruct him not to ever let me see the city's name on the cards and yet I can still easily predict his choice!
Here is my favorite trick based on the deep principal of Set theory.  Ok, maybe it is not too deep but the results are astounding!
Taking a deck of cards, you mention you have a prediction about these cards.  That means  it is very important to give the cards a really random shuffle.
You then give your volunteer half the deck and you both shuffle your half decks thoroughly.  Tell your volunteer to take a small amount(5-15) of cards from his half of the deck, turn them upside down and give them to you.  you do the same to him (doesn't matter how many cards you turn upside down as long as there is some left in your hand)
You then both shuffle the cards you have received into the deck in your hands in there upside down state.  so at this point both people will have some cards right side up some cards upside down.  You will follow the same procedure two more times.  It doesn't matter how many or what cards he or you are turning upside down and giving away. After all this is done put both half decks of cards together again (IMPORTANT: turn your entire half deck over when you place it on top of his)
Now you spread the cards out across a table top.  They should be a seemingly random mix of upside down and rigtside up cards. You then unfold your prediction slip which says something like:  11 cards will be black, 15 cards will be red, 6 will be clubs and 5 will be hearts and the hearts will also form a royal Flush!
They will be astounded by your amazingly detailed prediction.  What happens is that all the face up cards are the ones that were originally in your half deck.  This trick is self working.  All you do is to pick out which cards you want in your half of the deck and place them at the top of the deck to start.  Then just give him the random bottom half of the deck and you keep the pre-set ones.
Any questions?  Just email me at kevin@hallsofmagic.com

A: Here is a card trick from Edwin Connell's Elements of Abstract and Linear Algebra, page 18 (it can be found online).  I always do this trick to my undergraduate number theory class in the first minutes of the first day.  A few weeks later, after they've learned some modular arithmetic, we come back to the trick to see why it works.  I quote from Connell:
"Ask friends to pick out seven cards from a deck and then to select one
to look at without showing it to you. Take the six cards face down in your left hand
and the selected card in your right hand, and announce you will place the selected
card in with the other six, but they are not to know where. Put your hands behind
your back and place the selected card on top, and bring the seven cards in front in
your left hand. Ask your friends to give you a number between one and seven (not
allowing one). Suppose they say three. You move the top card to the bottom, then
the second card to the bottom, and then you turn over the third card, leaving it face
up on top. Then repeat the process, moving the top two cards to the bottom and
turning the third card face up on top. Continue until there is only one card face
down, and this will be the selected card."
When I do this trick, I always use big magician's cards (much easier for an audience to see), but a regular deck works too.  To get to the trick faster, I skip the first part and just pick 7 cards myself, showing them all the cards so they see nothing is funny (like two ace of spades or something).  I then spread the cards in one hand face-down and let a student pick one and show it to everyone else but me before I take it back face down.  When the student is showing the cards to the class I move the rest of the cards behind me so that before I get the card back I already have the rest behind my back.
You need to make sure students at the side of the room won't be able to see what you're doing behind your back (namely, putting the mystery card on the top of the deck), so stand close to the board.  Practice this with yourself many times first to be sure you can do it without screwing up. The hard part is remembering to keep the last card you reached in the count on the top of the deck; that same card will be used when you start the count in the next round.  If you stick it on the bottom before counting off cards again then you'll mess everything up.  For instance, if someone picks the number 3 then I start counting from the top of the deck and say (with hand movements in brackets) "One [put it under], two [put it under], three [turn it over, put it on top FACE UP and stop].  This [show face-up card to everyone] is not your card. [Put it back face-up on top]  One [now put it under], two [put it under], three [turn over and put on top FACE UP and stop].  This etc. etc."
Connell advises telling people to pick up a number from 1 to 7 but not allow 1.  In practice there's no need to tell people not to pick 1.  They never do (it's never happened to me). They don't pick 7 either.  And if they did pick 1, well, just turn over the top card and you're done!  Again, that never really happens.

A: The coffee mug trick is also called the Philipine Wine Trick and should be related to the Dirac String Trick, which you can find by a web search, for example here and also in my presentation Out of Line, where rotations in 3-space are related to the Projective Plane.
A knot trick, I am not sure you would call it magic, has been shown to children and academics in many places. It requires a pentoil knot of width 20" (say 100cm)  made of copper tubing, about 0.25" (7mm)  diameter (made by a university workshop) shown in the following diagram, but without the arrows and labels:

It also needs some nice flexible boating rope. The rope is wrapped round the $x,y$ pieces according to the rule
$$R=xyxyxy^{-1}x^{-1}y^{-1}x^{-1}y^{-1} $$
and the ends tied together, as in the following picture:

A member of the audience is then invited to come up and manipulate the loop of rope off the knot, starting by turning it upside down. This justifies the rule $R=1$. Of course the rule is the relation for the fundamental group of complement of the pentoil, which can, for the right audience, be deduced from the relations at each crossing given by the diagram

and can be easily demonstrated with the knot and rope. (The picture has no base point and so  seems to me related more to the notion of fundamental groupoid  than fundamental group.)
It is also of interest to have a copper trefoil rather than pentoil  around to compare the relations. One warning: the use of rope does not really model the fundamental group or groupoid, so be careful with a demo for the figure eight knot!
I did the demo for one teenager and he said:"Where did you get that formula?" This demo knot has been well travelled, for many different types of audience; on one occasion the airline lost my luggage with the rope and  I had to ask the taxi from the airport to to stop at a hardware store for me to buy d=some clothesline. I devised this trick for an undergraduate course in knot theory in the late 1970s.
You can also see a Knot Exhibition whose aim is to use the notion of knot to explain some basic methods of mathematics to the general public.

A: The "casting out nines" sanity check of calculations is dead simple to use (a small child can do it), but the proof requires a deeper knowledge of mathematics (more precisely of arithmetic ; my own students don't have access to it even though they know what series are and can diagonalize matrices!).

A: Matt Baker's book The Buena Vista Shuffle Club might tick the boxes. He is a math professor and card magician and the book uses a lot of math principles. It's published by Vanishing Inc.

A: Lay out 21 cards face up in three vertical lines. Have a friend pick out any card without telling you which card he/she has chosen. Have your friend tell you which line of cards the selected card is in, and make three stacks of cards, each stack being made from each line of cards. stack the three stacks on top of each other, placing the stack with the selected card between the other two stacks (IMPORTANT!).  lay out the cards again in the exact same set up (3 lines of 7 all face up) but here is the trick: when laying out the cards, flip them face up in a line every time. In other words, don't make one line at a time, but put a card in every line one at a time.  Have your friend again tell you which line has the selected card. Stack the cards again, the exact same way you did the first time.  One more time, lay out the cards the exact same way as the last time, one card per line, and again have your friend tell you which line has the selected card. Stack all the cards again one last time, again placing the line with the selected card between the other stacked cards.  now lay out all the cards face down, one at a time. while you're doing this, remember to count, because the 11th card you place down is the selected card.  from this point you can do whatever you can think of to make the trick "magical" and shock your friend by suddenly coming up with his/her card.

A: Start with a deck of 32 cards. Then the player should take a card and tell a number $n$ between 1 and 32 then you divide the stack in 2 smaller stacks and the player has to tell which of the stacks contains his chosen card. according to a rule dependend on that number you put that stack above or below the other stack.
After repeating this 5 times the chosen card should be exactly at position $n$. The rule has to depend on the way you want to deal cards (whether you turn around the deck and start dealing from the bottom, or you deal from the top and turn each single card around or you deal at first and then turn bost stacks around).
In one of the cases the rule was take $N-11$, find the representation in the system with base $-2$ and revert that presentation. ($0$ tells you to put the stack containing the chosen card on top, etc.).
I dont remeber this trick properly, it should not be too difficult to express the final position depending on the choices in some formula; but it is the only situation I know, in which the $-2$-system is useful.

A: i was about the to post another trick based on binary encoding in radices (or hamming codes) which has already been posted (see comment as well)
So i will post another one based on cyclic orderings (known also as "The Fitch Cheney Five-Card Trick")
excerpt (from here):

You hand a deck of cards to an audience and tell them to choose any
  five cards they wish. You collect the ve cards, look at them quickly,
  and then ask a volunteer to hide one of the cards after showing it to
  the audience. You place the remaining four cards face up in a line.
  You then tell someone in the room to go to the door and fetch your
  partner, who has been waiting outside. You take a seat in the back of
  the room somewhere out of sight. Your partner enters, takes a look at
  the four cards displayed, and correctly calls out the hidden card!
  Applause follows.

A: Requirements for audience: pen, paper, and calculator. You have nothing.
Offer the following instructions:

*

*Write down a whole number of any size without showing you.

*Just below it, write the same digits in a mixed up order.

*Subtract the smaller from the larger, and write down the result.

*In the resulting number, circle any digit which is not a 0.

*Ask them to tell you the other digits in the number which are not circled.

*You tell them the circled digit.

The key of course is that the resulting number in step 3 must be a multiple of 9 (obvious to readers here.) As the audience is reciting the digits in step 5, just keep track of the sum modulo 9. Take the result and subtract from 9 and that is the circled digit (except when the result is 0 then the circled digit is 9.)

A: How about the "Flash Mind Reader"


text:
Q: Extract date from file name I'm trying to extract the date from a filename and storing it to a variable and also needs to change the date format . If I have the name of the file consistent, can I go by position and extract the date?
File Name: GHDC_src_04142019_05_09_32.data.gz

looking the result of that date
04142019 as var=2019-04-14

A: Since you can "go by position," try:
$ name=GHDC_src_04142019_05_09_32.data.gz
$ echo "${name:13:4}-${name:9:2}-${name:11:2}"
2019-04-14

Or, to save in a variable:
name=GHDC_src_04142019_05_09_32.data.gz
var="${name:13:4}-${name:9:2}-${name:11:2}"

Since this uses pure bash, no subprocess needs to be started and no external command needs to be launched.  This makes this approach efficient.
The form ${name:offset:length} is called substring expansion.  It selects characters from $name starting at offset and continuing for length.  In our case, ${name:13:4} captures the year, ${name:9:2} the month, and ${name:11:2} the day.


text:
Q: 8051 External /WR signal not generated when UART bootloader is used after reset Goal of the project: To connect an LCD with 8051 as an external memory-mapped I/O device
Problem: Given the following details, my 8051 controller just does not generate an external RD/WR command as required for the rest of the code to work.
Previous work: I used 8051 port 3 pins to generate EN, R/W and RS signals and got it to work. Therefore, I know that my command sequence is working fine. However, this was a really inefficient way of using the LCD because the enable pulse was generated by setting and resetting a port pin. I wish to connect the LCD using the external WR/RD signals and mapping it as a memory-mapped IO device. I have worked through the timing diagrams and the overall block diagram is attached here. As you can see (in the block diagram), the R/W line of LCD is activated using the most significant 6 pins of port 2 so that the LCD gets activated only at the right memory addresses. This operation (implemented in an SPLD) also serves to ensure the delay required at the LCD to ensure the minimum setup time after Port 2 pins 0,1 are used to set inputs at R/W and RS signals of LCD.
Additional hardware info: I have attached a spice diagram to show how the rest of my 8051 is connected. The one thing that is not included there is this: "I use a momentary pushbutton and pull-down resistor for /PSEN, and hold that button when coming out of reset in order to force bootloader operation; then, after the bootloader has started, I release that button to eliminate drive fight issues on the /PSEN line. I use a header/jumper for the /EA input to ensure it is high. Note that if you use these hardware conditions to enter the bootloader when you come out of reset, then the Atmel bootloader is entered regardless of the values of BLJB, BSB, and SBV."
Software used: I am using the paulmon2 to test my code. Programming is done using Flip utility: Flip 3.4.7 through the serial port. A serial emulator program (TeraTerm) is used to communicate with the microcontroller. The microcontroller first executes the paulmon code as well as its extra commands that have been programmed into it before the current user code at 0x2000 location. An extra command allows the user to jump to this code using 'J' command and then giving the address for memory: 0x2000. This calls the current
program and executes it. This is where my code resides and executes from.
The addresses used to map LCD are the following:
LCD_INSTR_WR: 0xA8FF  ---> Used to write commands to LCD controller.
This includes all initialization and setup and management commands.
LCD_INSTR_RD: 0xA9FF ---> Used to read command. Done only to read the busy
flag or the current address counter. This is valid only for a single
instruction on the LCD.
LCD_DATA_WR: 0xAAFF ---> Used to write Data to the current address which has
been set either in DDRAM or CGRAM given the LCD_INSTR_WR above.
LCD_DATA_RD: 0xABFF ----> Used to read Data from the current address which
has been set either in DDRAM or CGRAM given the LCD_INSTR_WR above.

The code snippet I write in C to write the external memory:
//Global variables
volatile unsigned char xdata *LCD_INSTR_WR = (char xdata *) 0xA8FF;
volatile unsigned char xdata *LCD_INSTR_RD = (char xdata *) 0xA9FF;
volatile unsigned char xdata *LCD_DATA_WR = (char xdata *) 0xAAFF;
volatile unsigned char xdata *LCD_DATA_RD = (char xdata *) 0xABFF;
/// More code
//Write command example
lcdbusywait();
* LCD_DATA_WR = cc;

Earlier tests one to figure out the problem:

*

*I have tried writing to the memory locations above 2000 using the paulmon memory edit instructions and they write the memory locations alright. Even /WR command is generated in this case as observed (but I have not properly measured/counted the accesses and /WR edge changes.

*I have used the logic analyser to confirm that the address (and consequently RS and RW) and data (0x30H command in the beginning) are coming to the ports as expected. ALE is being generated.

*I have verified that AUXR register bit EXTRAM is set (AUXR = 0x0E). Also, since EXTRAM is set by default, I tried to remove my initialization code for AUXR completely and that didn't work either.

*I was not sure that the C code that I have written for the XRAM address accesses is correct. However, I went on to check the .asm file and (unless I am neglecting something very minute), the assembly code generated does assign a 0x30h value as immediate data to a register A and uses a "MOVX @dptr,A" instruction to write this value to external memory.

Finally, this is my first post at Stack overflow so the formatting may be off and I do realize this is an extremely long post. Apologies for that. Let me know if you need to see the code files or the compiled hex file or other details. All your help is deeply appreciated.

A: volatile unsigned char xdata *LCD_INSTR_WR = (char xdata *) 0xA8FF;

I guess LCD_INSTR_WR should have address0xA8FF value.
You can try by using
#define LCD_INSTR_WR  XBYTE[0xA8FF]

and then
LCD_INSTR_WR  = cc;

or
char xdata LCD_INSTR_WR  _at_ 0xA8FF;  //This will declare the LCD_INSTR_WR at location 0xA8FF-

You may need to look into the data sheet of the micro controller how to configure extrnal memory
LCD_INSTR_WR = cc;


text:
Q: Sending Outlook ical message with html table I've been working on a simple HTML form that will ask the user for info and when submitted, will have a PHP script email certain people with a calendar invite.
I also want the body of this calendar invite to have an HTML body - with an HTML table included.
With the code below I am able to send the email using PHP's mail function and it generates the appointment.  I can also add HTML content however the table gets stripped away.
I've read somewhere that the calendar invite only supports RTF.  This may be true however I've noticed on an OWA account the table does not get stripped away.
Can someone shed some light on my dilemma?  Thanks!

function sendIcalEmail($htmlmsg,$email,$meeting_date,$s_ccemail) {

$from_name = "sender name"
$from_address = "sender email"
$subject = "Test Appointment"; //Doubles as email subject and meeting subject in calendar
$meeting_description = "Description"

//Convert MYSQL datetime and construct iCal start, end and issue dates
$meetingstamp = strtotime($meeting_date . " EST");
$dtstart= gmdate("Ymd\THis\Z",$meetingstamp);
$dtend= gmdate("Ymd\THis\Z",$meetingstamp+7200);
$todaystamp = gmdate("Ymd\THis\Z");

//Create unique identifier
$cal_uid = date("Ymd")."T".date("His")."-".rand()."@mydomain.com";

//Create Mime Boundry
$mime_boundary = "----Meeting Booking----".md5(time());

//Create Email Headers
$headers = "From: Sender Name <noreply@domain.com>" . "\n";
$headers .= "Cc: ". $s_ccemail . "\n";
$headers .= "Reply-To: noreply@domain.com" . "\n";

$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
$headers .= "Content-class: urn:content-classes:calendarmessage\n";

//Create Email Body (HTML)
$message = "";
$message .= "--$mime_boundary\n";
$message .= "Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n";

$message .= $htmlmsg . "\r\n";

$message .= "--{$mime_boundary}\n";

$ical = "
BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:".$from_address."
DTSTART:".$dtstart."
DTEND:".$dtend."
LOCATION:
TRANSP:OPAQUE
SEQUENCE:0
UID:".$cal_uid."
DTSTAMP:".$todaystamp."
DESCRIPTION:".$meeting_description."
SUMMARY:".$subject."
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR";

$message .= "Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n";
$message .= "Content-Type: text/calendar;name="meeting.ics";method=REQUEST\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= $ical;

//SEND MAIL
$mail_sent = @mail( $email, $subject, $message, $headers );

if($mail_sent)
{
    return true;
} else {
    return false;
}}

A: I ran into a similar problem, but for me it was outlook 2003 would accept some formats, outlook 2007 would accept others, and go figure outlook 2010 accepted even others still.  I was able to get a working ICAL from php and posted it on the ExchangeCore Forums
Hopefully this will help you.


text:
Q: How to compute gradient of cumprod safely I'm trying to write a cumprod Op for a deep learning framework, the forward computation is simple, however there's some trouble with gradient computation.
Apparently, both Tensorflow and Theano are using the following bugged implementation :
def cumprod_grad(x, g):
    '''
    Returns cumprod gradient wrt x

    Args:
        x: vector
            original input
        g: vector
            upstream gradient
    '''
    fx = np.cumprod(x)
    return np.cumsum((fx*g)[::-1])[::-1] / x

This works most times, however in case x has an element of zero, the division will generate nan, which is incorrect.
Example:
x = np.array([1,0])
y = np.cumprod(x) # [1,0]
delx = cumprod_grad(x, np.array([1,1]))
# the correct delx is [1,1], however the output is [1, nan]

An O(n^2) fix is straightforward, however it's inefficient.
What would a efficient and vectorizable solution for this problem? Preferably an O(n) solution suitable for GPU implementation.


text:
Q: DropDownGallery Object? I was trying to follow this link to set up a drop down gallery on my ribbon bar using wpf and c#: http://msdn.microsoft.com/en-us/library/dd742868(v=VS.85).aspx
I cannot seem to initialize the dropdowngallery object on my ribbon bar in the xaml there is no option to create one... I have access to all the other ribbon controls besides the gallery controls in the xaml. There is a RibbonGallery object but not any specific gallery controls (DropDown, SplitButton, In-Ribbon) Am I missing something?

A: This blog post includes an example of how to add a Ribbon gallery in WPF. The link you include in your question is for the Win32/MFC version of the Ribbon control, which is different.


text:
Q: How to clone different rows of table with an unique event Making an ordering app. There is a div with a table containing all products with for each the price and a button to select it. There is a second div which containing selected products. So, i clone the selected product to put it in the second div. It runs but i had to make an event for each products and i would like to create an unique function using button class name to do this.
I tried to create a for() with no results but i'm a js beginner and i'va issues with my syntax
HTML

CHOOSE

            PRODUCT
            PRICE
            ADD TO CART

            Cherry
            6
            <button id="s1" class="item_button"></button>

            Peach
            8
            <button id="s2" class="item_button"></button>

            Strawberry
            12
            <button id="s3" class="item_button"></button>

            Banana
            7
            <button id="s4" class="item_button"></button>

            Apple
            7
            <button id="s5" class="item_button"></button>

YOUR CHOICE

JAVASCRIPT
var s0ne = document.getElementById('s1');
var sTwo = document.getElementById('s2');
var sThree = document.getElementById('s3');
var sFour = document.getElementById('s4');
var sFive = document.getElementById('s5');
let boxes = document.getElementById("starters")
let basket = document.getElementById("products_cart")

s0ne.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[1].cloneNode(true);
  basket.appendChild(clone);
}

sTwo.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[2].cloneNode(true);
  basket.appendChild(clone);
}

sThree.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[3].cloneNode(true);
  basket.appendChild(clone);
}

sFour.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[4].cloneNode(true);
  basket.appendChild(clone);
}

sFive.onclick = function() {
  let clone = boxes.getElementsByTagName("tr")[5].cloneNode(true);
  basket.appendChild(clone);
}

A: Use this javascript code :
add = function(e)
      {
        choices = document.getElementById('products_cart');
        choices.innerHTML=choices.innerHTML+e.target.parentNode.parentNode.innerHTML;

      }
      products = document.querySelectorAll('.item_button');

      for(i=0;i<products.length;i++)
         products[i].addEventListener('click',add,false);

A: Considering you can use jQuery:
let basket = document.getElementById("products_cart")

$('.item_button').on('click', function(e) {
 let target = $(e.currentTarget);
 let clone = target.parents('tr')[0].cloneNode(true);
 basket.appendChild(clone);
})

Using pure JS, you could do something like this:
let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
 button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
 let td = e.target.parentNode;
 let tr = td.parentNode;
 let clone = tr.cloneNode(true);
 basket.appendChild(clone);
}