How do you display code snippets in MS Word preserving format and syntax highlighting?

Question: Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.
I have tried to include code as regular text which looks awful and gets in the way when editing regular text.  I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects.  The code looks much better and is easier to avoid while editing the rest of the text.  However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.
Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.
Comment: Starting with Office 365, I don't know maybe even for Word 2013 or 2016. It has Online Addin called "Code Format" . Install that Office Addin and in your word doc you can just select all code (even multiple pages) and click convert it button from the Code Format addin and it converts it into a formatted color code with line numbers. I could not find the option to format without line numbers though !!! But nevertheless, not too bad !!
Comment: I have gone with a mixed solution. Copy with RTF formatting, pasting into OpenOffice Writer, removing the background (if there is any) and then pasting the code into MS Word.

For some reason I can't remove the background in Word :-(

Anyways, the ["Copy on steroids"](http://plugins.jetbrains.com/plugin/7198) plugin to do this in PhpStorm, WebStorm, PyCharm is awsome!
Comment: Outside of any specific add-in that would dedicate to format code the best solution is to use styles or alternatively images.
Styles are meant for formatting. I used to use many forks from Star Office to Libre Office today but I just got into Word and I found how to do it just by exploring the style config.
Just use Notepad++ to export RTF then use styles.

Some of the things I did is add a border, a background color I like,  check "Do not add spacing between the same style" or alike (I have the French GUI so I don't know the exact english caption) and anything you like.
Comment: Code Format is unavailable - but Easy Code Formatter here works pretty well: https://appsource.microsoft.com/en-us/product/office/WA104382008?tab=Overview
Comment: Just be careful with online code highlighting tool, once you submit your code, you never know what ll happen to your code. The tool provider may claimed ur code or anything. Just a warning though.
Comment: Also the Easy Code Formatter is not working anymore.
Comment: https://syntax-highlighter.k26.ch/ This site works great!
Answer: Here is the best way, for me, to add code inside word:

Go to Insert tab, Text section, click Object button (it's on the right)
Choose OpenDocument Text which will open a new embedded word document
Copy and paste your code from Visual Studio / Eclipse inside this embedded word page
Save and close

Advantages
The result looks very nice. Here are the advantages of this method:

The code keeps its original layout and colors
The code is separated from the rest of the document, as if it was a picture or a chart
Spelling errors won't be highlighted in the code (this is cool !)

And it takes only few seconds.
Comment: Can't see that option on Word 2011 on OSX :(
Comment: For Word 2011 on OSX use: Insert -> Object...Microsoft Word Document
Comment: Brilliant! I've been fiddling with styles, tables and other workarounds for years. This fixes everything in one go. Note that you also get the bonus of adding a caption to your code. I added a new label type "Listing" for brownie points :-)
Comment: @BetaRide No, it doesn't. I just used this on a document on a machine without OpenOffice installed. OpenDocument refers to a file format with support from MS Office among others: http://en.wikipedia.org/wiki/OpenDocument
Comment: how can we display whole code when it is longer than one page. In that case, whole object is shifting to new page and only shows whatever comes in that page. Is it possible that the object doesn't shift to new page and also shows whole code?
Comment: Please note tath this requires open/libre office to be installed on your machine.
Comment: If you are copying from Notepad++, then use Plugins -> NppExport -> Copy HTML to Clipboard
Comment: Other solutions below are better imo. The problem with this solutions is that if you embed code as an object then it is not search-able. Furthermore, if you have code that spans more than one page, then you have to create multiple objects for every page that your code spans.
Comment: any hints on how to include line numbers with this solution?
Comment: Doesn't seem to work as described in the MS Word 365 version.
Comment: Brilliant tip. Just to note, it doesn't work if copying code from IntelliJ (it is copied without syntax highlighting)
Comment: I have Windows 7, Word 2007 and do not have OpenOffice installed and still I am able to use this approach. My co-worker has Windows Vista, Word 2007 and OpenOffice 3.2 and cannot open the object created by me. He can create his own object, which he can edit not in separate window, but inside the main document (only some rulers are displayed around the object). EDIT: If I convert "openDocument Text" to "MS Word document", now he is able to edit my object.
Comment: Disadvantage is that you cannot select the text and you cannot copy the text to paste it elsewhere.
Comment: this totally depends on the source from where you copy the code!
copying from Microsoft Script Editor doesn't preserv any highlighting at all.
Comment: *** IMPORTANT for VS users: A LOT of these answers work. HOWEVER, Most will NOT work if you don't have correct options set in Visual Studio. In order to copy COLOR coding from Visual studio, you need to go to ***Tools > Option > Text Editor > Advanced > make sure the 'Copy rich text on copy/cut' check box is selected***. Once you do this, pretty much any of the answers to this question work.
Comment: Of course, this approach suffers from a lack of maintainability. What if you were to change your code mid/after writing your Word document. Then you have to apply that trick again to update the code snippet in your document. With LaTeX and the listings package, you'd just point to the source file and your code snippet would be updated the next time you compile your .tex file. No cop/paste involved. Plus, you'd get automatic syntax highlighting and line numbering.
Comment: I would suggest simply use snipping tool, u get an image and now simply insert that image.
Comment: It's not working for me. I have copied my html content from visual studio and pasted it as explained in the solution. It's rendering as plain text (all the html tags) and not showing any kind of formatting. Any Idea what could be the issue in my scenario?
Comment: Copying and pasting from Visual Studio Code works really well too.  The VS Code Dark theme looks bad, so make sure to use the default Light theme.
Comment: Beware, this solution seems to break 'Save as .PDF' feature in Office 365 Word version.
Edit: Printing as PDF option is still available, although that's not as comfortable as just saving as .PDF
Comment: This approach (inserting as OpenOffice Text object) makes it hard to select and copy the code. Just selecting the object and either CTRL-C or right-click--> copy doesn't then allow you to past elsewhere (e.g. in a text editor).
Comment: Magnificent. Also, some resources may help highlighting the code. For example: http://www.planetb.ca/syntax-highlight-word. Copy an HTML result to document. Voilà!
Comment: I get an error in Word 2021 on Windows requiring installation of OfficeLibre.
Comment: In Sublime text there is an option to copy as HTML in the edit menu (note you need to select your language in the view menu first). This is useful if you don't use Eclipse or MS code editing tools.
Comment: Not working for me. Maybe because I am getting the code from another server VS?
Comment: Hello this works awesome however when i cross reference the caption of opendocument text it inserts whole object too
Comment: Note that this only works when word saves the original formatting of the text. See [this microsoft link](https://support.office.com/en-us/article/Control-the-formatting-when-you-paste-text-20156a41-520e-48a6-8680-fb9ce15bf3d6#bm1).
Comment: After pasting it in the Open Document Text page format you can then Copy and Paste it in your MSword document from the ODT document maintaining the original formating and colors.
Comment: A lot of hoo-ha about `OpenDocument` format.  Why don't people just insert a second word document inside the first?  `Microsoft Word Document` is in the list as well.  The principle works nicely for my needs though.
Comment: Plus, this makes your code not selectable so people cannot copy it when shipped as docx or pdf.
Comment: Also worth noting, Search does not seem to work if the string you are search for is in the embedded document
Comment: This worked for me with Office 2019, but I found Home->Paste->Paste Special->Formatted Text to be slightly better.  The look is the same, but the text (code) is editable within the document. +1
Comment: I did not upvote this as it makes the document heavier, if you have to paste snippets multiple times throughout the document. It will make the document heavier and more time to load or edit.
Comment: Using this method with the NotePad++ method was optimal!
Comment: I like the outcome, but it has a great contra: it can't be easily copy-pasted while this would be very useful in case I need to write a guide with come command line.
Comment: https://syntax-highlighter.k26.ch After some tweaking I was able to get the site working again.
Answer: Download and install Notepad++ and do the following:

Paste your code in the window;
Select the programming language from the language menu;
Select the text to copy;
Right click and select Plugin commands -> Copy Text with Syntax Highlighting;
Paste it into MS Word and you are good to go!

Update 29/06/2013:
Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).
I use Copy all formats to clipboard and "paste as HTML" in MS word.
Comment: Thanks for this hint.  **Plugins -> NppExport -> Copy RTF to Clipboard** also works.
Comment: This worked very well.  In Word 2007+, to add a border and disable spell check: 1) select your code; 2) 'Home->Styles->Save selection as new Quick Style' (it is a drop button); 3) Name it 'Code' or similar; 4) Modify; 5) Format->Border (lower left) to add border; 6) Format->Language [X] Do not check spelling or grammar.  Now, you can apply the same formatting 'Code' to text pasted from NppExport.
Comment: This worked beautifully. I already had Notepad++ for other code projects, but never thought of using it. Combined with a Word style that added a faint blue background, border, and disabled spell check, it looks pretty good, and is fairly fast for a number of files, as opposed to methods involving file exports and imports. Although I wish there was a way to add it as a field that would automatically check the original .java files for updates, and keep the latest source code in the Word file.
Comment: @BennyNeugebauer : Line Number can be added by configure the Format->Numbering options, Define new number formate, remove the dot in first style. You can get to the Format option by either following @ Blazes 's steps OR in style select the new style->manage styles->Modify
Comment: This one works great, couldn't get the Word Document inside the Word Document to play nice. Folks this is the way to go!
Comment: Only disadvantage of this method is that it depends on language's syntax highlight support in Notepad++ (Like for example if you are using Drools). I think the same applies to eclipse, nevertheless both are great methods
Comment: @AndyH Thanks!  My right-click menu doesn't have *Plugin Commands*.
Comment: 0x6B6F77616C74: It works on 64-bit also. just download `NppExport` form [here](https://github.com/chcg/NPP_ExportPlugin/releases) and put it in c:/Program File/Notepad++/Plugins. Done
Comment: Unfortunately, any attempt to overlay a Word Style (such as "Normal + NoProofing")  destroys the coloring.
Comment: Does not seem to work with notepad++ v7.7 and MS Word 2016
Comment: Very good suggestion. However you don't get line numbers. Does anyone has a solution for that?
Comment: In Word 2010, the Style options are found by right clicking on the style in the Styles ribbon and choosing `Modify...`
Comment: I like this option better than gargamel's. Not that there's anything wrong with it but because my VS theme is dark and it looks pretty awful in a Word document.
Comment: This way is better simply because one can copy the code right from the Word doc instead of having the object open in a new window in order to copy.
Comment: By using Column Editor (Alt+C) you could add line numbers for code snippets
Comment: This approach completely lacks maintainability. If I change my source code, I want my document to reflect those changes automatically, not have to copy&paste everything all over again.
Comment: I created an openDocument like the top answer suggested, and pasted the code as described in this answer
Comment: For any simple documents with mere code samples this works amazingly beautifully.
Comment: It's worth to notice that it works only with the 32-bit version of Notepad++
Comment: For people using other themes there might be a black/brown/etc background which is unwanted when taking a print out of the code. In that case, head over to "Settings" -> "Style Configurator" and choose the Select Theme drop down menu at the top of the popup window. Choose the "Default" theme in it, and you're good to go.
Comment: Word likes to change characters like quotes and uses false spell checking here. Not a good solution.
Comment: If this doesn't work for anyone with NppExport 2.8, use this update: https://github.com/chcg/NPP_ExportPlugin/releases/tag/0.2.9.21
Comment: In Word, paste with "keep source formatting".  The code will look even better if we change the default font from "Courier New" to "Consolas".
Comment: Using the text object with this method is optimal.
Comment: When I started reading this answer I expected it to continue as "Download Notepad++... and use it instead of Word".
Answer: After reading a lot of related answers, I came across my own solution, which for me is the most suitable one.
Result looks like this:

As you can see, it is the same syntax highlighting like on Stack Overflow which is quite awesome.
Steps to reproduce:
on Stack Overflow

Goto Ask Question (preferably with Chrome)
Paste Code and add a language tag (e.g. Java) to get syntax hightlighting
Copy code from preview

in Word

Insert > Table > 1x1
Paste code (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting)
Table Design > Borders > No Border
Select code > Edit > Find > Replace
Search Document ^p (Paragraph Mark)
Replace With ^l (Manual Line Break)
(This is required to remove the gaps between some lines)
Select code again > Review > Language > check "Do not check spelling or grammar"
Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth

Sample code thanks to this guy
Comment: To add line numbers, you could insert a column to the left and include all line numbers in one cell.
Comment: This is my favorite answer, because it allows people reading the document to copy/paste the code.
Comment: Loses the pretty syntax highlighting for me on macOS big sur Word 16.50
Comment: @spartygw make sure you use "Paste Special -> Formatted Text (RTF)"
Comment: Under this approach, the code will be labeled as a table when doing auto-captioning.
Comment: I am loosing the syntax highlight even when I use "Paste Special -> Formatted Text (RTF)" in OSX Monterey
Answer: There is a nice Online Tool for that : https://planetb.troye.io/
Just copy the generated code and paste it into your word editing software. So far I've tried it on MS Word and WPS Writer, works really well.
Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).
One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages' syntax.
I tried many other options offered in other answers but I found this one to be the most efficient (quick and really effective).
There is also another online tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).
Input :

Output :
Comment: site no longer working.
Comment: Just to let others know, the output above is also how it will appear in the Word Document with the line numbers and green border and syntax highlighting
Comment: The line numbers are just a normal Word numbered list, so you can remove them easily once copy/pasted into Word by deselecting the numbered list option (Home>Paragraph>Numbering = None).
Comment: The only downside is if you want to copy and paste the code, you manually have to remove the line numbers.
Comment: This is the only solution here that worked for me - it's definitely the cleanest looking option!
Comment: "This application is currently unavailable" :(
Comment: @FLonLon yep not sure what happened. Apparently his [twitter](https://twitter.com/jamiebeach) is also suspended.
Comment: This works as expected, however, it is not possible to copy and reuse the code in word document in a straight way.
Comment: This site does not have JSON.  For JSON, I use http://www.bodurov.com/JsonFormatter/
Comment: @Fahmi Troye.io also seems down. This one is working: https://syntax-highlighter.k26.ch/
Comment: @Violet When I apply your suggesting, Home>Paragraph>Numbering = None to undo the numbering, the entire formatting is lost.  I want to remove the numbering but not the formatting.
Comment: This is absolutely fantastic.  For a part time coder like me, this gets the documentation process breeze.
Comment: @FLonLon This one works: https://syntax-highlighter.k26.ch
Comment: Alternative: https://syntax-highlighter.k26.ch/
Answer: I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.
Comment: But far from 100% fidelity. The copy process seems to remove a lot of formatting for some reason.
Comment: This works very well with Eclipse and OpenOffice Writer, by the way (I don't know of Eclipse/Word or VisualStudio/Writer, 'though).
Comment: Works, but since I have a black theme... results illegible. http://blog.wekeroad.com/wp-content/uploads/2007/10/codefile.gif
Comment: I wonder if it depends whether you use tabs or have Visual Studio convert tabs to spaces. I don't notice any issues with spaces.
Comment: Using spaces seems to fix any formatting errors. Kind of a pain, but it does work.
Comment: As of Office 2013 and VS 2015, this method works (even with the VS Dark theme)
Comment: simply disable "Copy As Html" extension if you use a dark theme and want to remove the dark background on WORD.
Comment: This literally does not work for me.  There must be a setting that is wrong.
Comment: Visual Studio didn't work for me too, but the idea is good and I used MATLAB for this purpose. The colors are preserved. MATLAB requires the file extension to be .c for correct highlighting, however.
Comment: In case you have a dark theme in VScode, then create one-cell table in MS-word, assign it a dark-grey backgroud (e.g. 25% of white, that is almost black) and paste code there
Answer: I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.
Comment: This seems cool but no way to install it in my word 2016... Error from word all time
Comment: @Jebik - if you're using a company account, perhaps your admin might have blocked the installations? I'm using it on 2016...What's your build number?
Comment: I had the version 16.0.4849.1000.
But as i said i have install 2 other supplément. So my compagny don't seem to block installation. It's jsut this extension i can't install. I don't even find it in store to be honest. From word when i open store and look for app this one is not in list
Comment: That means your Word is in a build version that doesn't support this addin.
Comment: Try updating word if you can, your version seems a bit old.
Comment: If somebody want to disable spell check, then : https://superuser.com/a/256258/681618
Answer: When I've done this, I've made extensive use of styles. It helps a lot.
What I do is create a paragraph style (perhaps called "Code Example" or something like that) which uses a monospaced font, carefully chosen tabs, a very light grey background, a thin black border above and below (that helps visibility a lot) and with spelling turned off. I also make sure that inter-line and inter-paragraph spacing are set right. I then create additional character styles on top (e.g., "Comment", "String", "Keyword", "Function Name Decl", "Variable Name Decl") which I layer on top; those set the color and whether the text is bold/italic. It's then pretty simple to go through and mark up a pasted example as being code and have it come out looking really good, and this is works well for short snippets. Long chunks of code probably should not normally be in something that's going to go on a dead tree. :-)
An advantage of doing it this way is that it is easy to adapt to whatever code you're doing; you don't have to rely on some IDE to figure out whatever is going on for you. (The main problem? Printed pages typically aren't as wide as editor windows so wrapping will suck...)
Comment: Would have been nice to share your style/template?
Comment: Thanks Donal for this information.
May ask though, how can I use intents to represent nested code lines? If I use a background color and border for my paragraph, when I use indent the whole block is moving.
Comment: Been doing the same for ages  - one big bugbear: whenever I apply the style, Word still red-underlines spelling problems. If I modify-style and select Format->Language, "Do not check spelling and grammar" is checked, and if I now close the format dialog with Ok, the lines will go - but they always appear until I do that.
Comment: @Rhubarb, add the "no check" attribute to your style. This works but is a fair amount of work if you want to maintain colors.
Comment: Copy from Visual Studio/SSMS/Notepad++ to get the colours. Then make and save this style in word: Font: (Default) Consolas, 9.5 pt, Do not check spelling or grammar, Indent:
    Left:  2.54 cm
    Right:  2.54 cm
    Line spacing:  single, Space
    Before:  16 pt
    After:  16 pt, Don't add space between paragraphs of the same style, Level 9
    Pattern: Clear (Custom Color(RGB(242,242,242))), Don't adjust space between Latin and Asian text, Don't adjust space between Asian text and numbers, Style: Linked, Automatically update, Show in the Styles gallery
    Based on: Normal
Answer: Try defining a style called 'code' and make it use a small fixed width font, it should look better then.
Use CTRL+SPACEBAR to reset style.
Comment: You won't keep syntax highlighting.
Comment: Of course you can keep syntax highlighting: [Create a Style without a font color](http://superuser.com/questions/360488/word-2010-create-a-style-without-a-font-color)
Comment: Syntax highlighting is overrated if we're talking a Word document here. But it is also easily implemented in a VB script that colors all text styled as "Code".
Comment: That's how I do it too with pretty good results, though I also turn off spelling/grammar checking for my "code" style.
Answer: Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?
Comment: It still won't keep syntax highlighting.
Comment: @Sk8erPeter: That's not necessarily the case.  Copy and paste is more than capable of transferring color information -- it does it all the time when I'd rather it didn't.  It depends on whether the source and destination applications both support the same schema for specifying it.
Comment: *** IMPORTANT*** for VS users: A LOT of these answers work. HOWEVER, Most will NOT work if you don't have correct options set in Visual Studio. In order to copy COLOR coding from Visual studio, you need to go to ***Tools > Option > Text Editor > Advanced > make sure the 'Copy rich text on copy/cut' check box is selected***. Once you do this, pretty much any of the answers to this question work.
Answer: If you are using Sublime Text, you can copy the code from Sublime to MS Word preserving the syntax highlighting.
Install the package called SublimeHighlight.
In Sublime, using your cursor, select the code you want to copy, right click it, select 'copy as rtf', and paste into MS Word.
Comment: This worked perfectly for me. Word extension completely messed up my code and comments, making in unreadable. This actually worked perfectly. I'll add that you can simply go to sublime, hit cmd+shift+P, go to `Install package` and type `highlight` there. It'll install it right away
Comment: Or just say "copy as HTML" in the edit menu
Comment: Higlight is working fine, however the format is getting messed up.
Answer: The best way I found is by using the table.
Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any color.

UPDATE  ------------------
From Word 2021, you can directly paste the code and it will preserve the formatting. No need to create the table.
Thank you @RdC1965 for mentioning this.
Comment: Yeah. thanks you very much!
Just create table 1x1, copy code from VSCode. Done!
Comment: At least with Word 2021, you just need to copy from VS Code and paste into Word. You don't need the 1x1 table.
Comment: This does not copy colors from vba. May work with other languages.
Comment: Never tried VBA. But it depends on IDE theme. Try to change the theme and then paste it.
Answer: In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use http://markup.su/highlighter/. It's very straight forward and supports several highlight themes and many programming languages. In my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).
Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.
This is what the code looks like finally.
Comment: Link is dead again... Just a heads up.
Comment: This was working great a week ago, however, as of 12/78/2017 the site http://markup.su/highlighter/ no longer works. Hopefully it will be back up soon.
Comment: @dark32 if I understand your issue correctly, you need to change the line spacing: https://support.office.com/en-us/article/Change-the-line-spacing-in-Word-1970e24a-441c-473d-918f-c6805237fbf4
Comment: Is there a way to change the font size? My code is very big and I want to fit it in few pages in word. Changing font size in word doesn't help
Comment: Could it be that you're not highlighting the text inside the textbox prior to changing the font size?
Comment: It changes the font size, but has no effect on the space between lines
Answer: This is a bit indirect, but it works very nicely.  Get LiveWriter and install this plugin:
http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html
Insert your code using the plugin into a blog post.  Select all and copy it to Word.
It looks great and can include line numbers.  It also spans pages decently.
HTH
Colby Africa
Comment: Requires account on Windows Live or Wordpress or some other of 10 blogging platforms.
Answer: Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.
Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.
Answer: You can use VS code to keep code format and highlighting. Directly copy and paste code from VS.
Comment: This one i found smartest answer for this question.
Thanks!
Answer: In my experience copy-paste from eclipse and Notepad++ works directly with word.
For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...
As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.
Hope I helped ;)
Answer: This is the simplest approach I follow. Consider I want to paste java code.

I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm
Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/
Then paste the preview code got from step 2 to the MS word. Finally it will look like this
Answer: you can simply use this Add-in on any office program.
Go to insert tab, then Get Add-ins, and search for Easy Syntax Highlighter
It supports

185 languages and 89 themes.

Automatic language detection.

Multi-language code highlighting.
Comment: This works in MS Word online too. Thanks a lot.
Comment: You're welcome.
Comment: WARNING (not *only* just a waste of time) Asks for your phone number and other personal information and then sends you to a broken link
Comment: Skip the link, Just go to the **insert** tab in the office program you use, then click **Get Add-ins**, and search for "Easy Syntax Highlighter" and add it. @RobHoff
Comment: It's more of a headache than an asset. Just removed it!
Answer: Answer for people trying to resolve this issue in 2019:
Most answers to this question are outdated by now. I wish there was a way to reinspect old questions and answers every now and then!
The method I found for this question that works with Office 365 and its associated programs can be found here.
Comment: I think it is suggested that some description from the link be added to the answer text in case the link dies eventually. https://meta.stackexchange.com/a/8259
Answer: Use a monospaced font like Lucida Console, which comes with Windows.  If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.
Answer: I'm using Word 2010 and I like copying and paste from a github gist. Just remember to keep source formatting!
I then change the font to DejaVu Sans Mono.
You can opt to copy with or without the numbering.
Answer: Copying into Eclipse and paste it in Word is also another option.
Answer: You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).
SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.
Comment: Doesn't work when pasting PHP code. Only the start and end brackets are highlighted :( Worked fine for Java though.
Answer: If you are using Intellij IDEA, just copy the code from the IDE and paste it in the word document.
Answer: A web site for coloration with lots of languages.
http://hilite.me/
You can host one yourself since it is open source. The code is on github.
Comment: hilite.me also works on Google docs!
Comment: Website is offline
Comment: @OgnyanDimitrov :) https would be nice
Answer: For people looking for a tool in 2023. Here's a tool which works with Word 2016 and 2019.
https://syntax-highlighter.k26.ch/
I made it, because there were many tools like it and all of them were going offline or stopped working. If you have feedback or problems, please create a GitHub issue. It's also very simple, small and fits into one HTML file. You can download or clone the repo and host it yourself.
Answer: There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.
What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.
Answer: If its Java source code copy it to Visual Studio and then copy it back to Word.
Answer: I was also looking for it and ended up creating something for my code display.
Here's a good way:

Create a rectangular form and place your text inside.
Change the font to Consolas and size ~10.
Change the text font to gray near-black (gray 25%, darker 75%)
Use darker colors to highlight your text if needed and choose one to be the contour.
Answer: I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.
Steps:

Create a 3x3 table.
Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option.

Make the adjustments to cells' spacing and columns' widths to get the desired aspect. (You will have to get in "Table Properties" for fine tuning).

Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)
Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering).

Apply "Code_numberline" to the first column, and "Code" to the 3 column.

Add a fill in the middle column.

Save that table style and enjoy!
Comment: If you copy and paste code you have to manually split lines to the rows.
Comment: Last time I used this method, I didn't have to. May be you need to select various rows.
Answer: The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.
Answer: Ok, this is weird, but to address the background color issue I paste in the text as normal, select the whole block, click on the highlighter tool to highlight (even if the highlight is set to "No Color"), and then I can style the text block without the background color of the text remaining white.  I am using VS 11 and Word 2010, but the problem has been around for a long time (see http://www.visualstudiodev.com/visual-studio-setup-installation/copypaste-code-from-vs-1305.shtml)
Answer: If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!
Comment: Or eclipse as well
Answer: From Powershell ISE copy and paste to Word.
Same with Visual Studio.
Answer: I've read and tried all the posts and I would like to give an overview of all the solutions. The best way is depending on your requirements. If there are only short snippets that are not longer than a page then go with Insert Object. If the code is longer than one page go with RTF Formatting.
Insert Textbox

No page break possible
Spell check available
Formatting can be ruined very quickly
In a document with thousands of pages Word 2016 started to make problems. At some point Word always crashed while trying to insert a new Textbox.

Insert Object > Document

No page break possible
No spell check
Formatting and content stays safe

RTF Formatting

Page breaks possible
Spell check available
Annoying line numbers when copying the code again from word
Online: Planet2b.ca http://www.planetb.ca/syntax-highlight-word
Offline: Highlight http://www.andre-simon.de/doku/highlight/highlight.php

Or any other wysiwyg-editor/online tool/library to style the code.
Some plug-ins/add-ons
All down or doesn't work anymore.
Comment: looks like a comment than an answer
Answer: Create a 'code' style.
To do this:

In 'Home' tab in the 'Styles' box, click drop down arrow and 'Create a Style'
name it 'code'
click Modify
Format

Then format as you wish (suggested options)

Paragraph -> Line and Page Breaks -> Keep lines together
Border -> Shading -> Fill -> grey

Then once your code style has been created. Paste your code into the document, highlight it, then navigate to:
home -> styles -> << click drop down arrow by styles >> -> code
This has the advantage that the code is now searchable within the document (unlike gargamel's solution), as well as being able to format code that is multiple pages.
Comment: And which style(s) do you recommend?
Comment: seems that the code style is not a default style. You can however create a code style yourself. For example, you may choose the following options: 1. click drop down arrow and 'Create a Style'. 2. name it 'code'. 3.click modify. 4. Format 5. paragraph -> wrap  6. border -> shading -> fill grey.
Answer: Just paste your code in MS Words, select it -> then right click -> Numbering. In this case MS Word will interpret your code as marker/numbered list.
Here is the screens:
Screen1.
Screen2.
Answer: If you're using TextMate (On OS X), use the "copy as rtf" command. It will place pretty-printed text onto the clipboard.
From there you can paste into word or anything else.
Answer: A quick approach I use is to use the Snipping Tool (already built in Microsoft tool) with stack overflow's preview.
Once I input my code into an Ask Question box, I then capture the preview and insert it into the MS Word document as a picture.

This above is the result, a picture, (not SO code ) you can put into word.
No worries about formatting, grammar checks, or downloading new software or
add-ins!
Answer:
Go to Dillinger.io (or any other on- or offline markdown editor)
Type your text and multiple programming languages' code snippets in easy markdown-style (just like you would right here on stackoverflow.com)
Copy & paste into e.g. MS Word

This works with almost any programming language and Markdown-Editor. E.g. VS Code is a Markdown-Editor, too. Just create a new .md-file, right-click it's tab and click Open Preview. That preview you can copy-paste just like explained above, too. You can also just save the .md-file as it is or (in the case of online services like Dillinger.io) explicitly export it e.g. to .html, .pdf, .rtf or .docx.
Answer: If you already have the document created with plenty of code snippets in it and you are racing against time (as I unfortunately was). Save the file as a .doc as opposed to .docx and voila! Worked for me. Phew!
NOTE: Obviously your document can't have fancy features from > word 2007.
NOTE 2: File size becomes bigger if this is a concern to you.
Answer: Simply right click and paste using the "Keep Source Formatting" option. I do this almost everyday to document my work. Further, you can set the 'default paste' for pasting from various soures in File/Options/Advanced/Cut,CopyPaste. Also useful: enable "Show paste options" in the same section of Word Options.
Note that all of the text properties from your Code Editor's theme (colors, fonts, etc.) will be added to the Stylesheet in your Word doc, so I would recommend that you not make any changes directly to the pasted text as that will add clutter to your stylesheet and subsequent pastes will not match.  It will be to your great advantage to do a quick study on using 'Styles' in Word (which are actually CSS). They are very powerful. Using Word's Stylesheet you can make global changes to the pasted text, but it will probably cause subsequent pasted text to add new styles.
Answer: You can paste your code into LINQPad.
Then copy from LINQPad into MS Word.
LINQPad supports following programming languages: C#, VB, SQL, ESQL and F#
Comment: This works very nicely. Remember to merge formatting when pasting into Word.
Answer: Hilite doesn't seem to be mentioned yet in the answers, so: Hilite supports lots of languages (20+), can be used online also via API, and is on Github (so you can clone, modify, and run it on your own if you don't trust the online service).
The online version can also be adjusted to one's needs via CSS rules.
I just found it some minutes ago since I needed a tool for copying xQuery into Word, but couldn't find a proper tool for doing so. The source program is baseX and for some reason, its formatting could not be transmitted to Word (also not via Keep format etc. when pasting). Also, many of the given answers are now, i.e. 06/2019, not working anymore or do not support xQuery. Hilite, however, did the job quite well.
Edit:
a code block is not part of the result, unfortunatelly, just the highlighting. Nevertheless, it's better than nothing and adjusting the result by adding a block around is still less work than formating every single line by hand
Answer:
What I do is I use Google Backup and Sync and put the docx file in the folder that syncs with Google Drive.
Then Open the file in chrome as google drive has functionality to parse docx file.
Then run this plugin https://workspace.google.com/marketplace/app/code_blocks/100740430168 which formats the code in different languages with good theme.
Once done save it and open the docx file in the system once it is synced.
Answer: The easiest way is to download the code blocks extension in Google Docs, then download the file as a Word doc.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: The easy way for me is to just copy and paste from VS code! You can change the VS code theme to a light theme which you prefer and then copy it directly (I used light modern theme).
Answer: I have created a solution here using VBA that you can run using CTRL+V. How to Setup VBA script in Word Document is 5 min job and I have explained it here.
Here is the output you get with the syntax highlighting and background colour removed.


Trying to install yeoman on ubuntu to use with nodejs and npm

Question: Using Ubuntu 13.10
I am trying to install yeoman using sudo npm install -g yo but it doesn't seem to work globally  both npm and nodejs are installed, however, I am not sure that they are installed correctly for use globally.  I cannot use npm i have to use sudo npm
To install node js I used
    $ sudo apt-get install python-software-properties
    $ sudo apt-add-repository ppa:chris-lea/node.js
    $ sudo apt-get update
    $ sudo apt-get install nodejs

When I use sudo npm install -g yo the output I get is
    /usr/bin/yo -> /usr/lib/node_modules/yo/cli.js

    > email@example.com postinstall /usr/lib/node_modules/yo
    > node ./scripts/doctor

    [Yeoman Doctor] Everything looks alright!

    firstname.lastname@example.com /usr/lib/node_modules/yo
    ├── firstname.lastname@example.com
    ├── firstname.lastname@example.com
    ├── firstname.lastname@example.com
    ├── email@example.com
    ├── email@example.com
    ├── email@example.com
    ├── email@example.com (firstname.lastname@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com)
    ├── email@example.com (email@example.com, firstname.lastname@example.com, supports-           email@example.com, email@example.com, firstname.lastname@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com, firstname.lastname@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com, firstname.lastname@example.com, email@example.com, word-
    email@example.com, email@example.com, firstname.lastname@example.com, email@example.com, email@example.com)
    ├── email@example.com (email@example.com, email@example.com,

    email@example.com)
    ├── firstname.lastname@example.com (firstname.lastname@example.com, firstname.lastname@example.com, email@example.com,
    email@example.com, firstname.lastname@example.com, firstname.lastname@example.com, email@example.com)
    └── email@example.com (firstname.lastname@example.com, email@example.com, email@example.com,
    email@example.com, firstname.lastname@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com,
    email@example.com, email@example.com, firstname.lastname@example.com, email@example.com,
    firstname.lastname@example.com, firstname.lastname@example.com, email@example.com, email@example.com, file-
    email@example.com, email@example.com, email@example.com, firstname.lastname@example.com, gruntfile-
    firstname.lastname@example.com, email@example.com)

So it appears that yeoman is installed correctly but that it isn't working - when I type yo nothing happens...  Do I need to put yo in my $PATH?  I'm not really sure how to do that..  Additionally, how do I configure npm so I don't have to use sudo npm?
Answer: It's worth noting that Ubuntu 13.10 is no longer officially supported, but that shouldn't make much of a difference for these instructions.
npm without sudo
First things first, let's get permissions sorted out. Most of the Node.js installation guides for Ubuntu instruct you to install Node.js from either the official repositories or from the chris-lea PPA. Either way, you'll end up installing Node.js and NPM using sudo, which leads to a permissions mess on development machines.
There's a question on StackOverflow about how to "fix" these permissions, although in most cases, you'll have to make your user the owner of /usr/local/lib/node_modules, which is super sketchy.
Instead, I think the best answer by far is to install Node.js using NVM. In addition to letting you run multiple versions of Node.js on the same computer, this option also keeps everything in your home folder, so your user owns NPM, and you don't have to mess around with sudo npm.
Using Yo
Once your permissions are sorted out, all of the steps you took to install and run Yeoman (npm install -g yo) should work just fine.
You will have to run nvm use v0.10 each time you start a new terminal session, however. You can get around this by adding a script to your .bashrc that will automatically run this for you at the beginning of each session,
Answer: You should check this post
it solves this problem


Why do my questions about collision entropy of languages get downvoted? And it's not just on this forum

Question: Why do my questions about collision entropy of languages, such as this one, get downvoted? And it's not just on this forum. The situation is similar on other forums about linguistics.
I have done quite a bit of research before asking that question, I've done the actual measurements, which you can see in the table. That is quite a bit more research than what's behind, for example, this question of mine, which got quite a few upvotes.
Answer: It may be because they don't clearly relate to the field of linguistics.
Asking about sound correspondences in the PIE etymology of an Armenian word is clearly a historical linguistics question, about how languages evolve over time. The likelihood of two randomly-chosen letters in a written text corresponding, on the other hand, isn't obviously a linguistic one. It's like how a question about text compression wouldn't necessarily be of interest to linguists, even though a good compression algorithm relies on properties of writing systems.
Entropy calculations absolutely can be linguistically interesting, but most of us can't read Czech, and in the absence of your actual paper it looks more like a codebreaking question than a linguistic one. You're asking whether this calculation relates to things that linguists have studied, which comes off as if you're searching for a connection to linguistics rather than investigating one.
The questions may be better-received if you focus on the linguistic aspects specifically. For example, how does the collision entropy change if you look at a phonemic representation of English? That might be a way to measure the "depth" of an orthography. Does this measurement give us any new insights into the difference between orthographies? Does it work for writing systems that aren't alphabets?
Comment: @FlatAssembler If that's the sort of answer you're looking for, I'd recommend rephrasing the question—asking specifically about the history of the English and French writing systems, for example.
Comment: @FlatAssembler To this linguist, that sounds like a reasonable question which has nothing to do with collision entropy
Comment: I asked it on a forum about linguistics because I expected the answer to come from historical linguistics. I expected the answer to be something along the lines of: "*Because the mantra 'English is spelt as it was pronounced around the invention of the printing press.' is not true. The silent 'e' is way more common today than final 'e' ever was in spoken English. Look at the numbers 1-10: the silent 'e' in 'five' (Old English 'fif') and 'nine' (Old English 'nigon') was never pronounced.*". Or something like that...


Uncaught SyntaxError: Unexpected token while reading JSON file

Question: My JSON file is:
{
    "myjson": [{
        "id": "1",
        "name": "x"
    }, {
        "id": "2",
        "name": "y"
    }]
}

And my HTML file to read it is like this:

But I get this error: Uncaught SyntaxError: Unexpected token in line 2
I can't change the JSON file, How can I solve the problem by changing HTML/JS code?
Comment: The JSON is invalid. The last property of an object does not have a semicolon after its value. See http://jsonlint.com/.
Comment: In addition, you can find such errors by using http://jsonlint.com/
Comment: Wait, wait, the JSON is valid according to JSON lint but your code does not show us how you parse it at all. There is just a function inside your code, it never gets called and it does not even decode JSON anywhere.
Comment: @somethinghere now the JSON is valid he edited his post, before it was not.
Comment: I solve that problem, but still I can't read it
Comment: How are you reading `external` json file ? When are you calling `myjson` function ?
Comment: You should load json file using ajax request and store the result into a variable and then call myjson method over that variable.
Answer: What you want to do is first parse the JSON file, then use your function for the array.
You can get the JSON from a file by using JQuery like this:
http://api.jquery.com/jquery.getjson/
$.getJSON("js/myjson.json", function(json){
    // json is an object which contains the array called "myjson"
    // now you can pass that array into your function like this:
    myjson(json.myjson);
})

If you don't want to use JQuery look how it's done without here:
How can I open a JSON file in JavaScript without jQuery?
Edit: Okay lets do it as a whole.
HTML:

Javascript:
function myjson(arr) {
    var out = "";
    var i;
    for(i = 0; i<arr.length; i++) {
        out += '' + arr[i].name + '
';
    }
    document.getElementById("id01").innerHTML = out;
}

function loadJSON(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

loadJSON('js/myjson.json', function(data){ myjson(data.myjson);}, function(xhr) {console.error(xhr); });

You can either put your Javascript inside your HTML with a script tag like

or put it into a seperate file and just link it in your HTML like this

Comment: **parse the JSON file** ?
Comment: @RayonDabre JQuery does that for you already. If you would get it as a string you would have to use JSON.parse(string) first to convert it into an object.
Comment: [Unless a tag for a framework/library is also included, a pure JavaScript answer is expected.](http://stackoverflow.com/tags/javascript/info)
Comment: @Quentin Edited in a solution without JQuery.
Comment: I get a bit confused, how should my HTML/JS code be right now ? to read that file
Comment: I assume you are not using JQuery Anderson? And if I understand you correctly you have the JSON located in one file and want to load it from there into your HTML page?
Comment: @user2415266 You have already put in _way more_ effort than necessary. There are dozens of questions about this on SO with great answers. +1 for you and boo to the downvoters.
Comment: @user2415266 yes that is, I should read that file on the server and load it's content in my HTML page. I did what you say, but it has an error : data is not defined
Comment: That is because I messed up, sorry about that I changed the code.. loadJSON needs a function as second argument, myjson(data.myjson) was wrong there. Now it should work.


beautify cURL download of JSON before writing to file

Question: I am using cURL 7.39.0 to call a REST webservice and write the response to a .json file:
curl -L-X POST -b cookies.txt -H "Content-Type: application/json" http://localhost:7001/web/service/url -d {"param1":"value1"} -o "C:\output\serviceName.json"

The response is written to the output file, but, without formatting:
{"status": "success","user": "name", "regId": "14420","subscriber": [{"memberFor":"3 years","lastLogin":"2 days ago"}]}

My questions are:

Is there a way to format the JSON response before writing it to the output file (like below)?
{
    "status": "success",
    "user": "name",
    "regId": "14420",
    "subscriber": [
        {
            "memberFor":"3 years",
            "lastLogin":"2 days ago"
        }
    ]
}

If formatting is not possible via cURL, I wish to write a simple batch file to automatically open the JSON output file and apply formatting. Something like:
@echo off
cls
"C:\Program Files\Notepad++\notepad++" "C:\output\serviceName.json"
pause

Are there any flags/options available in batch/console to achieve this?
Comment: You could try `python -m json.tool < filename.json > filename.json` but I'm not sure whether that'll successfully overwrite or give you a file-in-use error.  If error, then `python -m json.tool < filename.json > filename.tmp && move /y filename.tmp filename.json`.
Comment: cURL is basically a *copy* utility so it downloads the file as is. The second part of the question has many googlable duplicate questions on stackoverflow with various solutions.
Comment: @wOxxOm - Thanks! I found out that it is possible using python but I am unable to find the right syntax. I am using `"filename.json" | python -m json.tool` but I am getting - No JSON object can be decoded.
Can you please point me to the right syntax?
Comment: @BiscuitBoy maybe try `python -m json.tool < filename.json`.  If that doesn't work, you could try `type filename.json | python -m json.tool`.
Comment: @rojo - both the syntaxes work and format the json response in the cmd window itself. It doesn't format the JSON file that is written as output.
However, I will try your suggested solutions and mark as accepted.
Comment: If you decide you prefer the python beautifier after all, you ought to be able to redirect the output into a file.  `python -m json.tool < filename.json > beautified.json`
Comment: That works! But it creates two json files, one formatted and the other non-formatted. Is there a way to avoid the non-formatted file from being created.
Just curious. Apologies for pestering but I am having a hard time with Batch syntax as a beginner.
Answer: Edit: I found a solution using the htmlfile COM object, which should offer the fastest performance (at least for a single run) and does not require an Internet connection.  See the last solution in this answer.

Because you tagged this question with the [batch-file] tag, and because I found the challenge interesting, I wrote a hybrid batch + JScript script that'll beautify your JSON.  Since JScript 5.7 doesn't natively support the JSON object, this script uses an external json2.js, downloading it via XHR if it's not already been downloaded.  From there, it's a simple matter of calling JavaScript's familiar JSON.stringify() method with its beautify options.
Syntax:
json_generator | batfile.bat
    -or-
batfile.bat < jsonfile.json

Example usage:
beautify.bat < "C:\output\serviceName.json" > "C:\output\beautified.json"

This results in the following being saved as beautified.json:
{
        "status": "success",
        "user": "name",
        "regId": "14420",
        "subscriber": [
                {
                        "memberFor": "3 years",
                        "lastLogin": "2 days ago"
                }
        ]
}

The code:
@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end Batch / begin JScript hybrid chimera

var xObj = WSH.CreateObject('Microsoft.XMLHTTP'),
    fso = WSH.CreateObject('Scripting.FileSystemObject'),
    temp = WSH.CreateObject('WScript.Shell').Environment('Process')('temp'),
    j2lib = 'https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js',
    json = WSH.StdIn.ReadAll();

if (fso.FileExists(temp + '\\json2.js')) {
    j2lib = fso.OpenTextFile(temp + '\\json2.js', 1);
    eval(j2lib.ReadAll());
    j2lib.Close();
}
else {
    with (xObj) {
        open("GET", j2lib, true);
        setRequestHeader('User-Agent', 'XMLHTTP/1.0');
        send('');
    }

    while (xObj.readyState != 4) WSH.Sleep(50);
    eval(xObj.responseText);
    j2lib = fso.CreateTextFile(temp + '\\json2.js', true);
    j2lib.Write(xObj.responseText);
    j2lib.Close();
}

WSH.Echo(JSON.stringify(JSON.parse(json), null, '\t'));

Here's another solution using the same syntax that does not require downloading json2.js.  It avoids this by launching Internet Explorer invisibly, calling IE's built-in JSON methods, then silently closing IE again.  This is most likely going to be slower than the method above, and it could be blocked depending on machine security policies; but it does have the advantage of working without an Internet connection.
@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end Batch / begin JScript hybrid chimera

var IE = WSH.CreateObject('InternetExplorer.Application'),
    json = WSH.StdIn.ReadAll();

IE.Visible = 0;
IE.Navigate('about:blank');
while (IE.Busy || IE.ReadyState != 4) WSH.Sleep(25);

var JSON = IE.document.parentWindow.JSON,
    pretty = JSON.stringify(JSON.parse(json), null, "\t");

WSH.Echo(pretty);

IE.Quit();
try { while (IE && IE.Busy) WSH.Sleep(25); }
catch(e) {}

Here's one more solution, this time using a batch / HTA hybrid.  There's a <meta> tag forcing the HTA interpreter into IE9 compatibility, thus including
support for JSON methods.  This is faster than the IE method, but isn't completely invisible.  The HTA window flashes on the screen for an instant, then closes itself.

<meta http-equiv="x-ua-compatible" content="IE=9" />

The best solution I think is to use the scantily-documented htmlfile COM object.  Using the same trick with a <meta> tag to force it into IE9 compatibility as was demonstrated with the HTA solution above, the htmlfile COM object offers native support for JSON methods without requiring a library download, and without forking an additional windowed helper application.  It just loads a dll.
@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end batch / begin JScript hybrid chimera

var htmlfile = WSH.CreateObject('htmlfile'),
    json = WSH.StdIn.ReadAll();

htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');

var JSON = htmlfile.parentWindow.JSON,
    pretty = JSON.stringify(JSON.parse(json), null, '\t');

htmlfile.close(WSH.Echo(pretty));

Comment: @Foad That's a really good question. I noticed you left out the `x-ua-compatible` meta tag to force the `htmlfile` COM object into IE9 (or higher) compatibility, as well as cloning the method into the current runspace from `htmlfileObj.parentWindow`. But adding those missing elements doesn't really fix it either. I can find no way through this `htmlfile` object hack to expose `Object.getOwnPropertyDescriptor()` in a working fashion. Attempting to use it makes the script silently die, and `try` / `catch` catches a vague type error, like the thing you're trying to get the Property Descriptor...
Comment: WOW! @rojo - I didn't know there could be so many ways to make this work. I will try them all, especially, the last solution involving the `htmlfile` CON object.
Thank you very much!
Comment: Well, actually, the first solution, the one that downloads json2.js, is the fastest after json2.js has been downloaded.  But the last one is the fastest that doesn't require an Internet connection.
Comment: @BiscuitBoy Just curious, what is it you intend to do with the JSON data after it's been beautified?  If your intention is to scrape the data using text manipulation, you should re-evaluate your situation.  These JSON methods I'm suggesting all put the data into an object, then serialize it into a beautified string again.  You can cut out the middle man by doing something like `var sessData = JSON.parse(json);` then `WSH.Echo('Last login: ' + sessData.subscriber[0].lastLogin);` or similar.
Comment: **@rojo** -I am creating a batch file that makes use of cURL to call multiple web services that require a set of input params. My aim is to configure the URLs and inputs separately, call cURL for each configured URL and input , prettify and write the response to a json file, place the output files in a directory with a time-stamp. This directory wil be accessed by a testing team, who have their own plugin to verify test cases/ WS responses. At present , we are using some browser extensions to call each WS, save the JSON response, place all the responses in a directory, all done manually.
Comment: Upvoted now.Earlier, I didn't have the upvote privilege. Without a doubt, your answers were very helpful! They taught me tricks of BATCH programming that I couldn't learn from online docs. I will mark your answer as accepted once I try them out. Currently, I  have some other priorities which I am working on. So please bear with me. I reckon there is no time-frame to mark-as-accepted. Thank you
Comment: All your solutions taught me a thing or two (more than that, actually) about Batch scripting.But personally, I preferred using Python to format the output. Then again , you pointed me to the right syntax in one of your comments above. Hence, I mark your answer as accepted.
Mighthy thanks for your help, @rojo :)
Comment: Hi rojo, I asked a similar question [here](https://stackoverflow.com/q/65207848/4999991). Would appreciate it if you could take look at that one as well. Thanks in advance.
Comment: ... of isn't a standard object.  What's especially weird is that I have [used this method successfully](https://stackoverflow.com/a/34966337/1683264) to clone other object methods.  In any case, forcing the Chakra engine at the command line using `cscript //E:{1b7cd997-e5ff-4932-a7a6-2a9e636da385}` as [Kul-Tigin suggests](https://stackoverflow.com/a/65216915/1683264) is probably the only solution.
Answer: Just an update for oldish question.
https://stedolan.github.io/jq/ is pretty nice tool. By default, jq pretty-prints JSON output. So you can do
curl ... | jq .

"." is identity filter. See https://stedolan.github.io/jq/manual/#Invokingjq
Comment: While this link may answer the question, link only answers are discouraged on Stack Overflow, you can improve this answer by taking vital parts of the link and putting it into your answer, this makes sure your answer is still an answer if the link gets changed or removed :)
Answer: I believe this can all be done with Xidel, which prettyprints by default:
xidel -s --method=POST ^
--load-cookies="cookies.txt" ^
-H "Content-Type: application/json" ^
-d {"param1":"value1"} ^
http://localhost:7001/web/service/url ^
-e "$json"

Expected output:
{
  "status": "success",
  "user": "name",
  "regId": "14420"
  "subscriber": [
    {
      "memberFor":"3 years",
      "lastLogin":"2 days ago"
    }
  ]
}


document.children VS document.childNodes

Question: Interface Document inherits interface Node and specifies Node.childNodes. It works fine, but what is children? There's no such attribute in the specifications.
They work differently. If we have <!doctype html> node, document.childNodes contains it, but document.children doesn't.
Comment: http://stackoverflow.com/questions/7935689/what-is-the-difference-between-children-and-childnodes-in-javascript
Answer: From Matthew Flaschen's answer:

Element.children returns only element children, while Node.childNodes returns all node children. Note that elements are nodes, so both are available on elements.

<!doctype html> is a node is a DOM tree, so it is listed in childNodes, but it's a DocumentType node, not an Element, so it doesn't appear in children.
The reason you didn't find children in the spec you were looking at is probably because it's relatively new - it was added in DOM4 (which became a W3C Recommendation only in 2015).
If you need to traverse the Elements in the DOM tree (ignoring other node types -- such as text nodes), you will find children and related APIs (first/lastElementChild, previous/nextElementSibling) more convenient, but since they're newer, the old browsers don't universally support these APIs, so you should consult the compatibility tables and/or use a polyfill.


What's the deal with half-walls behind the kitchen cabinets? Can I cut into it?

Question: So I've recently moved in to a new house and the kitchen has two "blind cabinets" but no real good place to put my cat's food and water where it will be out of the way. So I got this brilliant idea that I could partition one of these blind corner cabinets and use the half that I wouldn't be able to reach very well as a feeding station. That cabinet butts up against a sort of half-wall at the back of the line of cabinets with the sink and I thought it might be possible to cut a hole in that drywall, then through the back of the cabinet to make an opening. I can take some photos later, but here's the kind of wall I'm talking about:

It's like this but not raised; it's flush with the countertop which just extends out a tad bit.
Long story short, I had a handyman over for something else so I asked if he could do this (I knew there were wires back there so I thought I would ask a professional) and he said sure no problem and knocked a hole in the drywall. Right into a stud. Which he didn't check for beforehand. So then he's like, I have to move this stud no problem. Blah, blah, boring events happen and I tell him not to come back because he seriously screwed up this other project I had hired him to do. So now I have a hole in the drywall and cuts in my cabinet back. There are also cuts into the stud but it's not completely severed.
And so that is the state my kitchen has been in for a few weeks as I try to figure out what to do next. My first thought is to just patch the drywall and move on with my life. On the other hand, I would really love to have that little nook so I don't have to step in my cat's food and water all the time.
I don't know a lot about studs and even less in this case...is that thing possibly holding important things up considering the countertop is mostly resting on the cabinets? The handyman apparently felt it would be trivial to move it but I don't really trust his judgement anymore.
What can I look for for clues to find out if this is a possibility? How much work does it sound like it might be? Should I patch it and move on? I think I'm a reasonable type of person.
Also, if you're having trouble picturing the feeding station, I was envisioning something like this (but not with bowls built in, just the nook part):

Thank you.
Comment: We really need pictures of your setup. In the top one, you can't put it where the dishwasher or the sink is, as I'd bet money that all the stubs come up or run through that wall. If the drain runs horizontally in your wall, like they prob do in this one if there's no basement, you're out of luck w/o entertaining some serious work.
Comment: Post pictures and we can help. Seriously. If it is actually a half-height wall, the handyman was right about a stud being trivial. (And you shouldn't blame him for hitting it... in a 2' span there is almost always one to hit.)
Comment: Oh I should also mention this "half wall" also doesn't extend up to the ceiling like the one in the example photo. It just goes to the wall.
Comment: That should work but watch out for power that will be run for the required outlets. the power may be run closer to the top of the 1/2 wall but not always.
Comment: The "blind cabinet" as you call it is often located in a manner that makes it seem like it would be a pain to swing back there every time you went to feed and water the cats. I would also mention that pets most often like to be feeling like they are part of the goings on of life in the kitchen and hiding the feeding area like you propose may make things feel exclusionary.
Comment: "Long story short..."? I'd like to hear the rest...
Answer: Aside from electrical and plumbing interference, you can do pretty much whatever you want with the framing. That wall is mostly decorative (it saved some money by not requiring the cabinet makers to finish the backs of the cabinets).
If you have smooth walls, open the drywall enough to work. Frame in your opening, replace the drywall, add corner bead or wood trim, and line the opening however you had planned.
If you want more specific help, strip out the kitchen's life story up there in your post, put up a photo of the actual project area, and we'll do our best.


Hiding symbol visibility while building a shared lib

Question: I have multiple objects files (lets say obj1.o, obj2.o) with which i am building a shared library (libapp.so). All associated objects so not had visibility flag as hidden when they were built, but in final so (libapp.so, see below), if i use visibility flag as hidden, will it hide all internal functions from outside libraries to use?
gcc -shared -fPIC -fvisibility=hidden obj1.o obj2.o -o libapp.so

EDIT:
As wRAR mentioned, i tried using versions cript to hide all symbol on final shared library. version script was written like-
file:libapp.version
{
    local: *;
};

and i built my shared library as:
gcc -shared -fPIC obj1.o obj2.o -o libapp.so -Wl,--version-script=libapp.version

Even after putting all symbol as local, i still can see in nm that all symbols are present. What i am doing wrong here?
Answer: -fvisibility is a compile-time option, so it has no effect at the link time. You can write a version script for ld to hide symbols at the link time.
Comment: I tried version script just as you mentioned. See my attempt on EDIT section of my question. Please let me know if i had used script in wrong way.


Storing data against a user who does not log in?

Question: On my website users do not log in, yet they can interact with the site. For example, they can vote on categories.
What would be the best way to prevent a user (even though they are not logged in) from voting for the same category more than once.
My initial thought was to store a user's IP address, when they vote, their IP along with the category voted for is stored in my database. Voting again for the same category will not have any effect.
I know proxies etc can circumnavigate this, but it's only meant to be a casual system to fool basic users.
Is there a better way to do this?
Comment: Anything, with enough effort, can be manipulated. As you said, the IP address can be changed by using a proxy. Everything else about the browser (user agent, installed fonts, OS, etc) come from the client, so these should not be relied on either.
Answer: You can start a session with session_start() and use AJAX to store vote information in the session. Similarly you can use AJAX call to your PHP script to see if a user can vote or not.
One downside to that is that if user removes his PHPSESSID cookie your session_start() will create new session, to avoid that you should use your own session control, any way you like, though it would have to store more unique information such as user-agent and the IP address as well as PHPSESSID.
Note, without any heavy counter-measures this can be fooled, one way or another, but you said yourself it's only meant to be a casual system to fool basic users.
Answer: If users do not login (do not authenticate themselves) on the site - then there is no 100% reliable way.
To my opinion, the best would be to use cookies(). for each user store in the cookie list of categories he has already voted, and deny a vote, if he retries.
But please note that if the guy cleans his cookies or come from another comupter - he will be able to vote again...
Again - there is no 100% reliable way
Answer: A simple way would be storing a cookie:
setcookie("user_voted", "1", time()+86400); // good for a day

Then:
if ($_COOKIE["user_voted"] == "1") {
    echo "You already voted!";
}

Not bullet proof, but you mentioned casual to fool basic users - that should do the trick then.
Answer: the two best solutions are either ip or cookies. but they are not 100% reliable


Is it possible to resurrect Jarl Maven Black-Briar?

Question: I killed Jarl Maven Black-Briar using a console command, however a later mission requires her to be alive for part of the mission.
Is it possible to resurrect her?
Answer: recycleactor 00019DD1

Another method of doing it, while in Riften:
prid 00019DD1
moveto player
ressurect 1

If the NPC is not shown after the moveto command, you might need to use enable after that.
Sources:
http://www.uesp.net/wiki/Skyrim:Maven_Black-Briar
http://www.uesp.net/wiki/Skyrim:Console
http://www.uesp.net/wiki/Skyrim:NPCs#Console_IDs
You can use this command on PC to resurrect her. Just press "^" (QWERTZ Keyboard) or "~" (QWERTY Keyboard) to open the console.
Comment: I didn't work but i found out how to resurrect her. So it's cool.
Comment: You might wanna tell why it did not work and what you did to solve it. This command worked for me, just checked it in Skyrim. If the reference ID is different, which is unlikely, you can always click on her body to get the ID displayed.


ECharts 3.0 custom map colors for USA States

Question: How can I color each state in US Map with a custom color?
This is the ECharts demo data I am using.

For example I want to color the states where Republican won with Red Color and Democrats in Blue color.
According to the documentation setting up the color inside the data element array should do it. But is not working.
I would like this map (colored) to look like this map (duotone).
Answer: This can be achieved by setting the colors in the visualMap data.

I've played around a little, and you can do the following:
Set the visualMap to a range of 0 to 1, making it binary, and assign each value to either Democrat or Republican.
visualMap: {
    left: 'right',
    min: 0,
    max: 1,
    inRange: {
        color: ['#DE0100', '#031BBB']
    },
    text: ['Republican','Democrat'],
    calculable: true
},

Next, in data, set the value of each state to either 0 or 1.
data:[
    {name: 'Alabama', value: 0},
    {name: 'Alaska', value: 0},
    {name: 'Arizona', value: 0},
    {name: 'Arkansas', value: 0},
    {name: 'California', value: 1},
    {name: 'Colorado', value: 1},
    {name: 'Connecticut', value: 1},
    {name: 'Delaware', value: 1},
    {name: 'District of Columbia', value: 0},
    {name: 'Florida', value: 0},
    {name: 'Georgia', value: 0},
    {name: 'Hawaii', value: 0},
    {name: 'Idaho', value: 0},
    {name: 'Illinois', value: 1},
    {name: 'Indiana', value: 0},
    {name: 'Iowa', value: 0},
    {name: 'Kansas', value: 0},
    {name: 'Kentucky', value: 0},
    {name: 'Louisiana', value: 0},
    {name: 'Maine', value: 1},
    {name: 'Maryland', value: 1},
    {name: 'Massachusetts', value: 1},
    {name: 'Michigan', value: 0},
    {name: 'Minnesota', value: 1},
    {name: 'Mississippi', value: 0},
    {name: 'Missouri', value: 0},
    {name: 'Montana', value: 0},
    {name: 'Nebraska', value: 0},
    {name: 'Nevada', value: 1},
    {name: 'New Hampshire', value: 1},
    {name: 'New Jersey', value: 1},
    {name: 'New Mexico', value: 1},
    {name: 'New York', value: 1},
    {name: 'North Carolina', value: 0},
    {name: 'North Dakota', value: 0},
    {name: 'Ohio', value: 0},
    {name: 'Oklahoma', value: 0},
    {name: 'Oregon', value: 1},
    {name: 'Pennsylvania', value: 0},
    {name: 'Rhode Island', value: 1},
    {name: 'South Carolina', value: 0},
    {name: 'South Dakota', value: 0},
    {name: 'Tennessee', value: 0},
    {name: 'Texas', value: 0},
    {name: 'Utah', value: 0},
    {name: 'Vermont', value: 1},
    {name: 'Virginia', value: 1},
    {name: 'Washington', value: 1},
    {name: 'West Virginia', value: 0},
    {name: 'Wisconsin', value: 0},
    {name: 'Wyoming', value: 0},
    {name: 'Puerto Rico', value: 0}
]

You can try it out by copy-pasting the data in the map demo
Comment: Great suggestion. Even though we give up some metric for each state like electoral vote or win% etc, we can handle the same through mouse over. Thank you


Unity-How to stop a moving object when the Camera sees it

Question: This is just a simple thing I want to do. I have my cube gameobject rotating and I want to make it so when the camera sees the cube, it stops rotating. If you could steer me in the right direction, I'd appreciate it. thank you
public class cubeMove : MonoBehaviour, MoveObject
{
public Renderer rend;

    public void Update () {

    rend = GetComponent<Renderer>();
    stopWhenSeen();
}
public void move()
{
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
public void stopWhenSeen()
{
    if (rend.enabled == false)
    {
        move();
    }
}

}
Answer: Implement the OnBecameVisible and OnBecameInvisible MonoBehaviour's message :
private visible = false ;

// OnBecameVisible is called when the renderer became visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameVisible()
{
    visible = true ;
}

// OnBecameInvisible is called when the renderer is no longer visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameInvisible()
{
    visible = false;
}

void Update()
{
    if( !visible )
        move() ;
}

public void move()
{
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}

Comment: would seen be a boolean value and is onBecameInvisible is predetermined function?
Comment: Yes to both questions..

You may find the documentation for OnBecameVisible() in the link below.

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnBecameVisible.html
Comment: I'm doing it, but it seems like it stops once I see it, but doesn't keep moving when I look away.
Comment: In fact, because your editor camera is rendering your object, `OnBecameInvisible` is never called.
Comment: I realised I made a typo in `OnBecameInvisible`, make sure the `v` is in lower-case.
Comment: I thought of something. the onbecamevisible function applies to the scene camera as well as the main camera. How would I make it so it only applies to the main camera?
Answer: https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
You could try the .isVisible bool in your update method.
Here is a thread with other suggestions:
http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html
Comment: I'm trying to do the onbecamevisible and onbecameinvisible, then in update, if public bool seen is true, then move, but the cube only moves for a second before stopping.
Comment: Did you check what the 'seen' bool says?

Does it switch as intended between true and false?
Comment: Seen is initialized as false, onbecameinvisible has seen be false, onbecamevisible has seen be true, and if !seen, then move().
Comment: Try remove the * Time.deltaTime part of your calculation, I suspect it might interfere in this case, then re-attempt to see if the rotation begins again.

I'm guessing something is misbehaving inside your move script.
Comment: then how I keep the cube rotating?
Comment: My bad, according to this example it should work with that approach.

https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

Is the object your script is on, the same object as the one you are trying to rotate?

Also, does your script inherit from MonoBehaviour?
Comment: Just noticed that MonoBehaviour is in front of the MoveObject inheritance.

What goes on inside the MoveObject inheritance?
Comment: I thought of something. the onbecamevisible function applies to the scene camera as well as the main camera. How would I make it so it only applies to the main camera?
Comment: Using this method you should be able to, see the link https://docs.unity3d.com/ScriptReference/Camera.OnWillRenderObject.html


In Rocksmith how do I "Reach master mode on a phase"?

Question: One of the 3 suggested goals to attempt literally states "Reach master mode on a phase". I'm not sure how to complete this task. I tried playing in song mode and improving myself in sections so they turn pink in the small song section overview, but it didn't register as completed so far.
Questions:

Am I maybe supposed to reach 100% score on that section to complete the goal?
Is a pink section the indication it's in master mode, or is master mode the "pro" mode where you don't see the notes anymore?
Can it be reached in song mode or do I need to go into practice mode?

Edit: To clarify the above 3 questions after completing the goal last week: 1. Just play the section without (too many) error a few times. 2. Pink is not master mode, the notes start fading out when master mode is active. 3. I completed it in song mode.
Answer: Basically, there are a couple of things that need to be done here for this to apply. Firstly, you need to make sure that "Master Mode" is enabled, and you also need to "level up" a phrase in a song in order For "Master Mode" to apply/kick in.
From the Ubisoft Forum it seems that not only is this incredibly vague, but also potentially mildly bugged:

Go into the options menu and play settings and make sure Master Mode is enabled.
If it is already enabled I would disable it, back out, then go back in and enable it.
Then play one of the songs that you have leveled up and as you nail fully leveled sections you should see Master Mode kick in.

This Reddit thread also provides a little more detail about what you should be seeing:

As far as I can tell, just getting 100% on a phrase in Learn a Song doesn't immediately throw you into Master mode. It takes a number of repetitions before the notes start to fade.
You need to play the phrase at 100% a few times (not sure how many), you will see the notes becoming fainter and fainter until they disappear, that's master level.


Proving $\dfrac{dN}{ds}=-\kappa T+\tau B$

Question: Currently revising for a differential geometry exam. The question I am working on is one of those types where the next part of the question follows from the last. I've gotten to the point where I have proven $T\cdot \dfrac{dN}{ds}=-\kappa$, and the next part is where I got stuck, which is to prove $\dfrac{dN}{ds}=-\kappa T+\tau B$. I looked at the mark scheme and it said "Follows from previous item, and $B=T\times N$". I simply don't see how it follows, though.
Comment: I know this is a meta question, but how can someone with 33 rep offer a +400 bounty?
Comment: What is your definition of the torsion $\tau$? In any case, you can see that $\frac{dN}{ds}$ belongs to the plane spanned by $T$ and $B$, i.e. that it is orthogonal to $N$, so that there are functions $\alpha$ and $\beta$ such that $\frac{dN}{ds}=\alpha T+\beta B$. Your previous calculations identifies $\alpha$ as $-\kappa$, and depending on how you define $\tau$, it should be obvious that $\beta=\tau$.
Comment: This wikipedia entry should prove useful to you http://en.wikipedia.org/wiki/Frenet%E2%80%93Serret_formulas
Comment: @alex.jordan I believe I once read bounty is taken automatically the moment you create it, so he had 433 before.
Answer: Since $B = T \times N$, differentiate with respect to $s$, obtaining $$\frac{dB}{ds} = -\tau N = \frac{dT}{ds} \times N + T \times \frac{dN}{ds} = T \times \frac{dN}{ds}$$ since $dT/ds= \kappa N$ and $N \times N = 0$. There are some conclusions to be drawn from this:

$dN/ds$ is not in the direction of $T$, else this cross product would be null.
$dN/ds$ is not in the direction of $B$ either, else you'd have $- \tau N = \kappa B$.
It is, however, in a linear combination of $T$ and $B$, or else its cross product couldn't be $N$.

It follows that we can state that $$\frac{dN}{ds} = a_1 T + a_2 B.$$ We need to determine $a_1$ and $a_2$. Since $$T \cdot \frac{dN}{ds} = -\kappa = T \cdot (a_1 T + a_2 B) = a_1$$ we have $a_1 = - \kappa$. I've used a little trick to find $a_2$. Notice that $$\frac{d}{ds}(B \cdot N) = \frac{dB}{ds} \cdot N + B \cdot \frac{dN}{ds},$$ therefore $$B \cdot \frac{dN}{ds} = \frac{d}{ds} (B \cdot N) - \frac{dB}{ds} \cdot N,$$ but $$B \cdot \frac{dN}{ds} = a_2$$ and $$B \cdot N = 0, \quad \frac{dB}{ds} \cdot N = (- \tau N) \cdot N = - \tau.$$ Therefore $a_2 = - (-\tau) = \tau$ and $$\frac{dN}{ds} = -\kappa T + \tau B.$$
Comment: @Holycow Do you understand the solution?
Answer: We are given a curve in ${\mathbb R}^3$:
$$\gamma: \quad s\mapsto{\bf x}(s)\ ,$$
parametrized with respect to arc length $s$. Assume that $\ddot {\bf x}(s)\ne{\bf 0}$.
Along this curve the so-called Frenet frame, a moving orthonormal frame, is defined as follows: Begin with
$$T=T(s):=\dot{\bf x}(s)\ .$$
This is a unit vector for all $s$. Therefore $\dot T\cdot T=0$, which means that $\dot T=\ddot{\bf x}\ne{\bf 0} $ is orthogonal to $T$. It follows that there is a uniquely defined unit vector $N$, depending on $s$, and a positive function $s\mapsto\kappa(s)$, the curvature of $\gamma$, such that
$$\dot T=\kappa\>N\ .\tag{1}$$
This normal vector $N$ shall be the second vector of our frame. The third vector is the binormal $B:=T\times N$, which is automatically a unit vector. We now have our orthonormal frame $(T,N, B)$.
The so-called Frenet formulas are a system of coupled differential equations for $T$, $N$, and $B$. The first of these equations is $(1)$. The second is about $\dot N$. As $N$ is a unit vector for all $s$ its derivative is orthogonal to $N$ and therefore is a linear combination of $T$ and $B$:
$$\dot N=\alpha T +\tau B\ .$$
According to the rules of vector algebra one has
$$\alpha=T\cdot\dot N={d\over dt}(T\cdot N)-\dot T\cdot N=-\kappa\ ,$$
so that we definitively can write
$$\dot N=-\kappa T+\tau B\ ,\tag{2}$$
where the function $s\mapsto\tau(s)$ is called the torsion of the curve $\gamma$.
The third of the Frenet equations is obtained by differentiating the defining equation of $B$:
$$\dot B=\dot T\times N+T\times \dot N={\bf 0}+T\times(-\kappa T+\tau B)=\tau\ T\times B\ .$$
According to the rules of vector algebra we therefore obtain
$$\dot B=-\tau\> N\ .\tag{3}$$
Equations $(1)-(3)$ can be condensed to the matrix equation
$$\left[\matrix{\dot T\cr\dot N\cr\dot B\cr}\right]=\left[\matrix{0&\kappa&0\cr-\kappa&0&\tau\cr0&-\tau&0\cr}\right]\>\left[\matrix{T\cr N\cr B\cr}\right]\ .$$
Comment: noice work, thanks
Answer: $\frac{dN}{ds}$ is orthogonal to $N$ by differentiating the identity $N\cdot N=1$. So, $\frac{dN}{ds}$ is a combination of $T$ and $B$, i.e. $\frac{dN}{ds}=x\,T+y\,B$. Comparing the "known identity" $T\cdot \frac{dN}{ds}=-\kappa$ with
$$
T\cdot \frac{dN}{ds}=x\,(T\cdot T)+y\,(T\cdot B)=x
$$
($T$ is perpendicular to $B$ by the definition of $B$) you get $x=-\kappa$.
I suppose that $\tau$ hasn't been defined yet and $\tau:=y$ is then defined by this equation, altghough it was not completely clear from your question. (If $\tau$ has already been defined by the equation $\frac{dB}{ds}=-\tau N$, then you derive $y=\tau$ by differentiating $B=T\times N$.)
Answer: You know that dNds must be orthogonal to N. Hence dN/ds=CT+DB for some C(s) and D(s). You have shown that C=−κ. How do you think you should go about finding D?


The shapes of the array expressions do not conform, Fortran 90

Question: I am trying to achieve the same goal that is gained with the last line of the code, but with a do loop that you can see in my code. The problem is that when I try to form the loop with the command like
CURV_KVEC%KNOTS(knot)=(/0.d0/)

I get an error
The shapes of the array expressions do not conform.

Any help will be appreciated! Thanks.
cdegree=2
count=5

do knot=0,cdegree+count
if (knot.le.cdegree) then
    CURV_KVEC%KNOTS(knot)=0.d0
    test(knot+1)=0.d0
elseif (knot.ge.count) then
    test(knot+1)=1.d0
    CURV_KVEC%KNOTS(knot)=1.d0
elseif(nvec.eq.0) then
    num=num+1
    do kn=1,cdegree
       CURV_KVEC%KNOTS(knot+kn-1)=0.5d0  !dble(num)/(dble(count-cdegree-1)/dble(cdegree)+1.d0)
        test(knot+kn)=0.5d0  !dble(num)/(dble(count-cdegree-1)/dble(cdegree)+1.d0)
        nvec=cdegree-1
    enddo
elseif(nvec.ne.0) then
    nvec=nvec-1
endif
write(14,*)knot,num,nvec,test(knot+1)
enddo

! CURV_KVEC%KNOTS(0:CURV_KVEC%LENGTH) = (/0.D0,0.D0,0.D0,0.5d0,0.5d0,1.d0,1.d0,1.d0/)

Answer: CURV_KVEC%KNOTS(knot) is an array element, a scalar. (/0.d0/) denotes an array of length 1. These are not the same thing...
Simply writing
CURV_KVEC%KNOTS(knot) = 0.d0

would do the trick.
Comment: Except the line that is commented out in the code sample has various values, not all of which are zero.  So this solution is not equivalent.
Comment: I finally figured it out! The problem was outside the code that you can see above. The expressions commented in the middle (!dble(num)... and so on) give the value of 0.5. I commented them in order to check if there was a problem there. The values calculated are the components of a knot vector of a NURBS curve so they need to be updated depending on the curve's degree and control points' number. Actually there's no problem in the above code. There is just another loop outside, that causes the above code to be executed twice and some values are not restored before the second loop. Thanks a lot!
Answer: Equating two arrays, the arrays on the left and right hand sides have to have the same shapes.  Here, with 1D arrays that simply means that they have the same lengths.   Since the left-hand side has a run-time determined length of CURV_KVEC%LENGTH + 1, you can't use a fixed-length constant array on the right-hand side.
If you want all elements of the array on the LHS to have the same value, then you can use a scaler on the right-hand side, as suggested by @Alexander Vogt, and that value will be broadcast to the array.   I'm interpreting the example code to be that you want different values.  If you want the same values, this is the best solution.
Comment: I finally figured it out! The problem was outside the code that you can see above. The expressions commented in the middle (!dble(num)... and so on) give the value of 0.5. I commented them in order to check if there was a problem there. The values calculated are the components of a knot vector of a NURBS curve so they need to be updated depending on the curve's degree and control points' number. Actually there's no problem in the above code. There is just another loop outside, that causes the above code to be executed twice and some values are not restored before the second loop. Thanks a lot!


Unable to pass array variable in email with codeigniter

Question: Here is my code
$success = $this->user_model->get_user($user_id);
//$success variable contains some array values
if($success){
    $this->email->from('email@example.com'));
    $this->email->to($success->email);
    $this->email->subject('New user registration and update');
    $message = $this->load->view('email/view_adduser', $success, true);
    $this->email->message($message);
    $this->email->send();
 }

Email is sucessfully sent, but data aren't displaying there.
And here is my email view template(email/view_adduser.php)

Hello Sir/Madam

Your Login credientials are provided below

Please <a href="<?php echo base_url().'admin'; ?>" >Login
To access your account

Username & Password : - <?php echo $success->username;?>

Here username is not displaying in the email.
Anybody have any idea???
Thanks in advance
Comment: You should be using $username in the view as CI converts it for you
Comment: Are you positive the array contains the proper data? Maybe try using `var_dump($success)` and see what is displayed.
Answer: If you want to access the data in your view as $success->username then you should wrap the user object in an array when passing it to the view like this:
$message = $this->load->view('email/view_adduser', array('success' => $success), true);

Otherwise you can access the data directly without the $success object, i.e: $username instead of $success->username


Understanding recursion in λ calculus

Question:
In recursion for λ calculus, I was wondering why the following two are equal

(λx.g (x x)) (λx.g (x x))
g ((λx.g (x x)) (λx.g (x x)))

How shall I understand g ((λx.g (x x)) (λx.g (x x)))?

I am learning λ calculus from Wikipedia, and I can understand many of its basics.
Thanks!
Answer: When you evaluate $(\lambda x.g(x x)) (y)$, it is equivalent to $g(y y)$ (This is called $\beta$-reduction). Therefore, when you do
$$
(\lambda \, x.g(x \, x))(\lambda \, x.g(x \, x))
$$
You can see the second parenthesis as the "big chunk you're putting as an argument in your abstraction on the left", so that
$$
(\lambda \, x.g(x \, x))(\, Y \,) \quad \underset{\beta}{\rightarrow} \quad g(\,Y \quad Y\,) \quad \rightarrow \quad g( (\lambda \, x.g(x\, x))  (\lambda\, x.g(x \,x)) )
$$
(I used the right-arrow to say "reads as". This is standard for $\beta$-reduction.)
Wikipedia is not a place to learn, it's a reference. You should use it only to take a look at fun stuff or recall something you've already learned. For learning, you should use books or tutorials, it's a better idea. Try this as a tutorial :
http://classes.soe.ucsc.edu/cmps112/Spring03/readings/lambdacalculus/introduction.html
Hope that helps,

Understanding recursion in λ calculus


Ubuntu on virtualbox no internet connection

Question: Trying to access the internet on a virtualbox VM with Ubuntu-20.04.1 LTS and a WiFi adapter.
The VM has 2 network adapters. NAT and host only with a host-only adapter with static IP address.
The netplan config looks like:
network:
  ethernets:
    enp0s3:
            dhcp4: yes
    enp0s8:
            addresses: [192.168.56.3/24]
            gateway4: 192.168.56.1
            nameservers:
                    addresses: [126.96.36.199, 18.104.22.168]
  version: 2

and ip addr show says:
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:dd:a6:04 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86264sec preferred_lft 86264sec
    inet6 fe80::a00:27ff:fedd:a604/64 scope link
       valid_lft forever preferred_lft forever
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:0e:27:7d brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.3/24 brd 192.168.56.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe0e:277d/64 scope link
       valid_lft forever preferred_lft forever

enp0s3 is assigned a 10.x.x.x address but still it doesn't work, whereas another VM which gets the same 10.x.x.x address does work.
What am I missing?
Answer: Probably, it is an issue with the default route. You don't need the Gateway and DNS for host-only network!
You may check it using: ip route show
Remove them from the configuration, so default Gateway goes to interface with NAT/DHCP configuration. Also DNS which does not seems to affect, but keep reasonable clean configuration.
Comment: Remove them from configuration??
This needs more details.
Comment: Ok. That makes sense. Thanks.
Comment: @KenIngram Yeah the answer was specific to OP case, as he already knows where is and already modified it the configuration. It is hard  cover every configuration layer: (1)  OP uses netplan config in `/etc/netplan/` see ref https://netplan.io/examples/#configuration (2) or some use switched network manger (3) VirtualBox has also a common configuration for host-only interfaces.