Sunday, December 31, 2017

Congratulations Vietnam

As General William DePuy told the French general who said the South Vietnamese were incapable of fighting : "They kicked your ass at Dien Bien Phu!"

Congratulations and congratulations Korea! Again!

China as reliable as ever. And congratulations India on picking up the pace going the other way - out of the top-50 now. Behind Saudi, Bangladesh, Peru..

CountryTeam sizeP1P2P3P4P5P6TotalRankAwardsLeaderDeputy leader
AllMFGSBHM
Republic of Korea6514239142222417016000Yongjin SongSuyoung Choi
People's Republic of China664225042193115925100Yijun YaoSihui Zhang
Vietnam664236042211415534110Anh Vinh LêBá Khánh Trình Lê
United States of America664229042231214843300Po-Shen LohBrian Lawrence
Islamic Republic of Iran66423204217914252310Omid Hatami VarzanehSeyed Hesam Firouzi
Japan66412104223713462220Yasuo MoritaKeiko Tasaki
Singapore66422603722413172121Yan Loi WongXinghuan Ai
Contestant [][←]CountryP1P2P3P4P5P6TotalRankAward
Amirmojtaba SabourIslamic Republic of Iran770777351Gold medal
Yuta TakayaJapan770777351Gold medal
Hữu Quốc Huy HoàngVietnam770777351Gold medal
Qiuyu RenPeople's Republic of China770774324Gold medal
Aleksandre SaatashviliGeorgia770773315Gold medal
James LinUnited States of America770772306Gold medal

Are you, like me, wondering what was so tricky about Problem 3? (I'm clueless, ICYW). Nice variation on the curve of pursuit problem I first saw in Brilliant Tutorials (lifted from Irodov).

Problem 3. A hunter and an invisible rabbit play a game in the Euclidean plane. The rabbit’s starting point, A0, and the hunter’s starting point, B0, are the same. After n−1 rounds of the game, the rabbit is at point An−1 and the hunter is at point Bn−1.

In the n th round of the game, three things occur in order.
(i) The rabbit moves invisibly to a point An such that the distance between An−1 and An is exactly 1.
(ii) A tracking device reports a point Pn to the hunter. The only guarantee provided by the tracking device to the hunter is that the distance between Pn and An is at most 1.

(iii) The hunter moves visibly to a point Bn such that the distance between Bn−1 and Bn is exactly 1.

Is it always possible, no matter how the rabbit moves, and no matter what points are reported by the tracking device, for the hunter to choose her moves so that after 109 rounds she can ensure that the distance between her and the rabbit is at most 100?

Tuesday, December 19, 2017

Use Bitcoin to Solve the "Who" Problem

Per Geoff Smart and Randy Street, Who mistakes happen when :

Menageries (managers) :

  • Are unclear about what is needed in a job
  • Have a weak flow of candidates
  • Do not trust their ability to pick out the right candidate from a pool of similar looking candidates
  • Lose candidates they really want to join their team


How?

Decide what the MISSION is. What are you trying to accomplish as a team and what will the new hire's mission be. What OUTCOMES must the new recruit realize? Be clear about what COMPETENCIES successful candidates have that enable them to be A players. Be clear about the cultural fit - what needs to exist for ALIGNMENT.

How?

  • Create a SCORECARD. This tells you how you'll judge the performance of the candidate after a few months on the job.
  • SOURCE lots!!! of high quality candidates.
  • SELECT qualifying candidates.
  • SELL them on why this position is right for them.


How to efficiently whittle down a bunch?

Use a good phone screen :

  • Could you tell me about your career goals?
  • What are you really good at professionally?
  • What are you not good at or not interested in doing professionally?
  • Who were your last five bosses and how will they rate your performance on a scale of 1-10 when we talk to them?


How?

Use a good top-grading interview :

  • What were you hired to do?
  • What accomplishments are you most proud of?
  • What were some of the low points in that job?
  • Who were the people you worked with? Specifically :
  • -- what was your boss' name and how do you spell that? What was it like working with that person? What will he/she tell me were your strengths and areas for improvement?
  • -- tell me about the team you inherited? How would you rate them? What changes did you make? How would you rate the team when you left?
  • Why did you leave?



Sunday, December 10, 2017

I Hired Your Resume, But I Got You -- Jay Jordan

From the super book "Who" : Street/Smart Who : Critical Competencies for A Players
  • . Efficiency. Able to produce significant output with minimal wasted effort.
  • . Honesty/integrity. Does not cut corners ethieafly. Earns trust and maintains Confidence. Does What is right, not just what is politically expedient. Speaks plainly and truthfully.
  • . Organization and planning : Plans, organizes, dchedules, and budgets in an efficient productive manner, Focuses on key priorities.
  • . Aggressiveness- Moves  quickly and takes a forceful Stand without being overly abrasive.
  • . Follow through on Commitments : Lives  up to Verbal and written agreements, regardless of personal cost,
  • - Intelligence. Learns quickly. Demonstrates ability to quickly and proficiently understand and absorb new in formation. 
  • . Analytical skills. Able to structure and process qualltative or quantitative data and draw insightful conclusions from it. Exhibits a probing mind and achieves penetrating insights.
  • - Attention to detail. Does not let important details Slip through the cracks or derail a project.
  • - Persistence. Demonstrates tenacity and Willingness to go the distance to get something done.
  • . Proactivity. Acts without being told what to do. Brings new ideas to the company.

  • Ability to Hire A Players (for managers), Sources, selects, and sells A Players to join a company,
  • Ability to develop People (for managers). Coaches people in their current roles to improve performance, and prepares them for future roles.
  • . Flexibility/adaptability. Adjusts quickly to changing priorities and conditions. Copes effectively with complexity and change.
  • , Calm under pressure. Maintains stable performance when under heavy pressure or stress.
  • . Strategic thinking/visioning. Able to see and communicate the big picture in an inspiring way. Determines opportunities and threats through comprehensive analysis of current and future trends.
  • . Creativity/innovation. Generates new and innovative approaches to problems.
  • - Enthusiasm. Exhibits passion and excitement over work. Has a can-do attitude.
  • . Work ethic. Possesses a strong willingness to work hard and sometimes long hours to get the job done. Has a track record of working hard.
  • . High standards. Expects personal performance and team performance to be nothing short of the best.
  • . Listening skills. Lets others speak and seeks to understand their viewpoints.
  • - Openness to criticism and ideas. Often solicits feedback and reacts calmly to criticism or negative feedback.
  • - Communication. Speaks and writes clearly and articulately without being overly verbose or talkative. Maintains this Standard in all forms of Written Communication including email. 
  • Teamwork. Reaches out to peers and cooperates with supervisors to establish an overall collaborative working relationship.
  • Persuasion. Able to convince others to pursue a course of action.
Bill Johnson, CEO of Heinz' wish list : Chemistry, Commitment, Coachability, Controlled Ego, Requisite Intellect.

Windows Startup Folder in 5 Seconds

Open a File Explorer window (using icon from Taskbar if necessary )


Then, type startup in the box as shown


Press Enter and you're done. You'll get to something like

C:\Users\\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

How you're supposed to know that? I don't know. Why did I want to get here? So I could put in a link to Capture2Text!! The greatest piece of Utilityware the world has ever seen

Saturday, December 09, 2017

Clark's Tips a la Howard

http://clark.com/

Know : You have a health credit report too... (Milliman, Ingenix)

You can (if you ever need to) order pills of 2x the strength, which cost the same, and then cut them in half for each administration - saving yourself 50%. Nice. See me in 50 years!

Sunday, November 26, 2017

Adorable Honesty : Personal History

Some lessons were impressed on me by reverse example. When I was young, I perceived grown-ups behaving quite oddly at times. I remember being shocked or dismayed by things I observed and making silent vows not to behave as they did when I grew up. For instance, my mother, when confronted with a line waiting at the movies, would go up to the box oflice and say, “I am Mrs.  Eugene Meyer of The Washington Post,” and demand to be taken in and seated. At that time, she did indeed get in. l cringed with embarrassment and hoped the ground would swallow me up. It had such a lasting effect on me that I have never been able to deal with headwaiters in restaurants who put you “in Siberia” rather than the better part of the restaurant. I just go meekly to Siberia.


Saturday, November 25, 2017

Defensive Programming

Programming Defensively :

Consider designing your code to make bugs easier to track down. Bugs that raise an error far away from the root cause are harder to track down.

For example:

  • Declare the expected argument types of one or more of your functions.
  • You can either have the platform's evaluator perform the argument type checking or write your own code to check.
  • Include assertions in your code that check for a condition that holds if things are in working order.
  • Write a function to check that a condition holds and raise an error if the condition does not hold.


Then and Now : How FANGS Loom Large


From visualcapitalist.com

Saturday, November 11, 2017

How To "Variablize" Your Environment Settings

You have

export bad_guy='machiavelli_the_3.12.3'
export path = 'x:y:z:/usr/lib/machiavelli_the_3.12.3'
export bad_home='/usr/lib/share/utils/machiavelli_the_3.12.3/bin'

you get the idea. You want to upgrade machiavelli to an even more devious character - once - in ONE place.

So you'd rather see :

export bad_guy='machiavelli_the_3.12.3'
export path = 'x:y:z:/usr/lib/'$bad_guy''
export bad_home='/usr/lib/share/utils/'$bad_guy'/bin'

You get the idea..

This is the best I have .. not even sure how to google this.. Pretty inelegant. Also,  you can't just pipe your existing file through this in your editor :(

#!/usr/bin/perl

$file = shift;
$var = shift;

$sys = "grep $var $file";

$var_line = `$sys`;

$val = (split( /'/ , $var_line ))[1];

print $var_line ;

$sys = q{grep -v }.$var.' '.$file.q{ | perl -p -e 's/\b}.$var_val.q{\b/\047\$}.$var.q{\047/;'};

$rem = `$sys`;

print $rem;

How It's Done : Dov Moran

Congratulations. Enough said..

http://nocamels.com/2013/03/dov-moran-talks-to-nocamels-about-sandisk-comigo-modu/

Sunday, October 29, 2017

The Magic of Taek Joo Kim, Now Working for AMZN

Man, I love it! Omnibox timer - you can tell Chrome to remind you to get up and walk - and it'll literally "tell" you - it pronounces your message.

How does the man do it?

https://github.com/taicki/omnibox-timer

https://chrome.google.com/webstore/detail/omnibox-timer/iooaeaogjngpihndkcednkblomlkaaif?hl=en-US

Handy Excel Hacks

https://excelwithbusiness.com/wp-content/uploads/2017/10/100-Excel-Tips_EwB.pdf

Paste Special : ALT E S V
Also, Transpose can be very handy at times.
Add Multiple Rows
F4 for Absolute Reference - did you know that pressing F4 repeatedly will toggle through the various combos?

A treasure trove!

Saturday, October 28, 2017

Excel howto : Quickly ID a Column of Text Using a Perl Hack

Okay, that doesn't make sense. Here's what you want to do :


A
B
C
C
A
A
D
D
D
A

to turn to (you guessed it - for use in Pivot tables)

1
2
3
3
1
1
4
4
4
1

select all and pipe through (Yes, you see why you want Cygwin :)

perl -n -e 'BEGIN{%table=(); $count=0} chomp; unless( defined $table{$_} ){ $table{$_} = $count++; } print "$_," and print $table{$_} and print "\n";'

This will give you
A,1
A,1
B,2
...

So you can easily paste this back in by doing the smart import..

Here's a braindead way to show text in Excel pivot table values area :

https://www.youtube.com/watch?v=wslp2BqHuz8

Shame on Contextures Inc.

Sunday, October 22, 2017

Keyboard Shortcuts for Google Chrome

Which imbecile came up with CTRL-D for "bookmark"? CTRL-D is for "duplicate" - every i knows that. Surely?

What if you need to change it? (to duplicate that is)

You open a new tab and, in the URL field, type :

chrome://extensions

Now, scroll to the bottom and click on "Get more extensions"

That takes you to the Chrome Web Store. In the search field, enter "keyboard shortcuts".

Then, pick the one by Mike Crittenden.

Install it and then, in the space next to the URL field in Chrome (on the right), you'll see the icon for this tool .. it has a 'Q' in the top-left corner..


Right-click on this guy and, in the drop-down menu, choose Options. How are you supposed to know this? Don't ask me :)


Now, you get to place where you can easily add new shortcuts. Nice work.

https://github.com/mikecrittenden/chrome-shortkeys

Friday, October 20, 2017

Wer ist das Genius?

Who is the genius behind this super blog that teaches you amazing stuff. He ain't no Jacob Vandenplas or Rachel Tatman (just kidding :) probably better ) but ... he's..


Armed with a 4.0 GPA in Computer Science from Napoli (Bachelors and Masters), he's now at :

Senior Data Scientist
Hive | Centrica Hive Limited
May 2017 – Present
Cambridge, United Kingdom
I work with a large team of data scientists across a number of projects. My responsibilities include:
- design of Machine Learning models to integrate into real-time products
- manage stakeholders communicating results and set expectations
- mentoring other data scientists

Congratulations mensch. Great stuff.

Sunday, October 08, 2017

Supercell (Clash of C) Nails It


http://supercell.com/en/our-story/

We’ve found that the best quality work comes from small teams in which every single member is passionate about what they do. Often times when teams become bigger, processes, bureaucracy and even politics emerge, and the work just isn’t fun anymore. That’s why we wanted to create an organizational model made up of very small teams, or “cells” as we call them. Supercell is a collection of these cells. Each game comes from a cell, and they all operate extremely independently and have complete control over their own roadmap. Our organizational model is optimized for speed and passion, not for control.

Friday, October 06, 2017

How to Paste Image in Clipboard into (at) a Cell in Excel

Well "into" means "at" a particular cell.

Try it with just on Excel file open. You'll see that Excel always dumps the picture right at the top. What a pain? Thanks Satya for another dose of crappiness. Where would Mac be without something really crappy to compare to?

Anyway, the workaround is

Have a scratchpad Excel doc open.
Paste the image from clipboard into *that* scratchpad.
Right-click on the image in the scratchpad and choose "Copy"
Now, go back to *your* working Excel doc and select the cell you want to paste at.
Do Ctrl-V

Thursday, October 05, 2017

Excel Pivot Table Torture

Python pandas can do it, but, of course, M$ Excel can't. When will Redmond learn from open s?

You want values that are plain text, not numbers. What can you do?

The first order of business is to create an accompanying column of numbers - a unique number for each text item. That is, if your column has

A
A
B
D
E
F
A
C

Then, you want

A 0
A 0
B 1
D 2
E 3
F 4
A 0
C 5

perl -n -e 'BEGIN{%table=(); $count=0} chomp; unless( defined $table{$_} ){   $table{$_} = $count++; } print "$_," and print $table{$_} and print "\n";' 

(Meaning, copy that one column into a text editor - aka NEdit - in Cygwin, and then pipe through the above perl script :) (See why you need unix? :)

Then, you run into the other roadblock. You add this column to your existing Table, and the Pivot Tables simply don't see it. WT*? Luckily, "how to refresh pivot table options" with Google delivers - and works..

Tuesday, October 03, 2017

A Horizontal Bar Chart (Plot) with Seaborn (Python)

 Why? Coz Seaborn gives you something better looking by default :)


series1= starterDf['col_of_interest'].value_counts()


df_for_sns = series1.rename_axis('col_of_interest').reset_index(name='counts') #change counts if you w

import seaborn as sns
sns.set_style('white') # if you want..

sns.barplot( y='col_of_interest', x="counts", data=df_for_sns)
sns.despine( top=True, bottom=True , left=True, right=True )


Thanks to : https://stackoverflow.com/questions/47136436/python-pandas-convert-value-counts-output-to-dataframe

Sunday, September 24, 2017

So You Want to Work with Andrew Ng?

The following would also be helpful, but isn’t required:
  • A degree in CS is preferred. Completion of Computer Science or other relevant MOOCs will also be helpful. 
  • Experience with big data systems such as Hadoop, Spark, Nifi, Storm, HDFS, NFS, Lustre, Presto, Hive, AWS Redshift, AWS Athena.
  • Experience leading an engineering team
  • Experience with industrial data-driven/AI/Machine learning projects
  • Strong willingness to help junior engineers
  • Mandarin (Chinese) fluency is a plus
We hope you will fit well with our team’s culture:

Strong work ethic. All of us believe in our work’s ability to change human lives, and consequently work not just smart, but also hard. It’s not unusual to see some team members in the office late into the evening; many of us routinely work and study 70+ hours a week.

Growth mindset: We are eager to teach you new skills and invest in your continual development. But learning is hard work, so this is something we hope you’ll want to do.

Good team member: We care and watch out for each other. We’re humble individually, and go after big goals together.

Flexibility: Since we’re an early stage company, you should be flexible in your tasks and do whatever is needed, ranging from dirty work like data cleaning, to high-level work like algorithm design.

Wednesday, September 13, 2017

Massimo Banzi (Arduino) Bookshelf

  • Out of Control
  • Art of the Digital Age (Bruce Wands)
  • Total Interaction
  • Designing Interactions (Bill Moggridge)
  • The semantic turn
  • METAMAGICAL THEMAS (Douglas Hofstadter)
  • Human-Computer Interaction
  • Physical Computing
  • past tense, future sense
  • DEUTSCHE STANDARDS
  • pROCESS
  • Open Design Now
  • World Changing - a User's Guide for the 21st Century (Alex Steffen. "passivhaus buildings, biomimicry, intros by Van Jones and Bill McKibben (350.org) )
  • Paper Prototyping (about designing user interfaces) (Carolyn Snyder)


Thursday, August 17, 2017

How to Be a Good Codebreaker : Wolf (William) Friedman

Under mental equipment he would also include the faculty of being able to concentrate on a problem for rather long periods of time, without distraction, nervous irritability, and impatience. The strain under which cryptanalytic studies are necessarily conducted is quite severe and too long-continued application has the effect of draining nervous energy to an unwholesome degree, so that a word or two of caution may not here be out of place. One should continue at work only so long as a peaceful, calm spirit prevails, whether the work is fruitful or not. 'But just as soon as the mind becomes wearied with the exertion, or just as soon as a feeling of hopelessness or mental fatigue intervenes, it is better to stop completely and turn to other activities, rest, or play. It is essential to remark that systematization and orderliness of work are aids in reducing nervous tension and irritability. On this account it is better to take the time to prepare the data carefully, rewrite the text if necessary, and so on, rather than work with slipshod, incomplete, or improperly arranged material.

https://www.nsa.gov/portals/75/documents/news-features/declassified-documents/military-cryptanalysis/mil_crypt_I.pdf

How Will You Find the Longest Words Shakespeare Used (Perl)

  1. Get them text from : https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt
  2. vi ./shakesp.txt    # get rid of the obviously easy stuff - a look through tells you up to what point (sonnets start) you can safely delete :)
  3. perl -n -000 -e 'print unless /^\s*\d+\s*$|ELECTRONIC|^\s*the\s+end\s*$|project\s+gutenberg|etext/i;' ./shakesp.txt > shakeclean.txt
  4. perl -p -e 's/[^a-zA-Z\047]/\n/g; s/(.)/\L$1/g;' shakeclean.txt | perl -nl -e 'chomp; print if length > 13;' | sort | uniq | perl -n -0'' -e '@words = split( "\n" ); @sorted = sort { length $b <=> length $a } @words; $longest = join "\n", @sorted; print "$longest";'
honorificabilitudinitatibus (Love's Labour Lost)
anthropophaginian
indistinguishable
undistinguishable
incomprehensible
superserviceable
circumscription
disproportioned
distemperatures
distinguishment
enfranchisement
excommunication
extraordinarily
flibbertigibbet
impossibilities
indistinguish'd
interchangeably
interchangement
interrogatories
misconstruction
notwithstanding
particularities
perpendicularly
portotartarossa
praeclarissimus
prognostication
superstitiously
transformations
uncompassionate
uncomprehensive
undistinguished
unreconciliable
accommodations
accomplishment
acknowledgment
administration
affectionately
apprenticehood
carnarvonshire
circumstantial
consanguineous
considerations
conspectuities
constantinople
contemptuously
contumeliously
correspondence
counterfeiting
determinations
discomfortable
discontentedly
disparagements
distemperature
entertainments
fortifications
halfpennyworth
handicraftsmen
imperceiverant
inconveniences
insurrection's
intelligencing
inter'gatories
interpretation
leicestershire
mephostophilus
nebuchadnezzar
northumberland
oscorbidulchos
preposterously
principalities
proportionable
reconciliation
sovereignvours
superscription
transformation
unaccommodated
understandings
unpremeditated
unproportion'd
unquestionable
unthankfulness
voluptuousness

Saturday, August 12, 2017

Oh For a Better Python Debugger

Are there any debuggers that, when they tell you they run into an issue when you did "continue" can also tell you what steps to take to get the line before you get the problem?

Someone should make one and upgrade the pdb likewise.

Wednesday, August 09, 2017

The Underwhelming Genius of Guido van Rossum's Underlings

$ pip install XlsxWriter
Requirement already satisfied: XlsxWriter in c:\users\USERNAME\appdata\local\programs\python\python35-32\lib\site-packages

$ python -m XlsxWriter
/usr/bin/python: No module named XlsxWriter

Why can't python or even pip for that matter put out a warning about PYTHONPATH? What single mom with three kids and a mortgage needs to find out she has cancer before they put this in?

Das mensch suggests python -m pip install is a panacea. Really?

 $ python -m pip install XlsxWriter
Collecting XlsxWriter
  Using cached XlsxWriter-0.9.8-py2.py3-none-any.whl
Installing collected packages: XlsxWriter
Successfully installed XlsxWriter-0.9.8
 $ python -m !$
python -m XlsxWriter
C:\Users\USER\AppData\Local\Continuum\Anaconda3\envs\aind\python.exe: No module named XlsxWriter

WT*!!??

Okay, reading and reading and reading (for all the protesting CS folks do about user experience, when it comes to free stuff, unless you're the product (think GOOG)) you get what you pay for. Why can't they issue a warning saying (say) "importing usually uses the name in lowercase completely". Why not ease the pain?

So, if I set my PYTHONPATH and then do python -m xlsxwriter.worksheet, I actually do get something.. 

Getting Windows and Cygwin to Behave and then Using du for Disk Space Accounting

One use of Cygwin Windows can't match (I mean a unix feature Redmond hasn't heard of) is du

Your disk space is running low and of course Windows gives you accounting info - accurate but useless info - it doesn't tell you who the culprits are..

Unix - via Cygwin can help

But...

user@host /cygdrive/c
$ echo  `ls -d */ | grep ocumen | perl -p -e 's%/.*$%%;  s/\h/\134 /g;'`
Documents\ and\ Settings

user@host /cygdrive/c
$ du -ks  `ls -d */ | grep ocumen | perl -p -e 's%/.*$%%;  s/\h/\134 /g;'`
du: cannot access 'Documents\': No such file or directory
du: cannot access 'and\': No such file or directory
du: cannot access 'Settings': No such file or directory

Smell a rat? It's been bugging me for too long..

The ultimate goal is to be able to do $ for dir in `asdfdas` ; do ; du -ks $dir ; done ... But, it's turning out to be harder than I thought..

Here's the other problem. You do

$ for dir in `ls -d */` ; do ; echo $dir ; done
you get

Documents
and
Settings

which will make du curse you. Here's my workaround : 

for dir in `ls -1 -d */ | perl -p -e 's@/.*@@; s/\h/\%20/g; '`
do
tdir=`echo $dir | perl -p -e 's/%20/ /g;'`
du -ks "$tdir"
done

You're first giving bash's for loop a list with spaces in filenames substituted with %20. This is just so the for loop behaves (yes, you can mess with the IFS variable)
Then, you create a variable with the filename restored.
Then you call du on this new variable

Sunday, July 30, 2017

Inspire Your Co-Workers with a Screensaver

So you want to display quotes on your computer's locked screen when you're not at your desk. There's one way I know. Looking for a powerpoint that will sequence through slides like in kiosk mode? Sorry, that's not an option (yet) in Windows 10 for the lock screen.

Save your ppt as JPEG images (File > Save As > change the format - the name you provide will be a folder containing each slide)

That done, click on the Window (Start button) on the left of your taskbar and then on the Gear (settings). You'll launch Windows Settings.

Here, in the search box, type "lock" (it might suggest "add a folder to your lock screen slideshow", but don't jump the gun.

At the new menu, change the "Background" option from "Windows Spotlight" to "Slideshow" (drop down)

Then, under "Choose albums for your slideshow", add your new folder.

Then, click on "Advanced slideshow settings" and adjust "When my PC is inactive, show lock .." and "Turn off screen after slideshow has played for".. to your choice.

And that's it. Hit WIN-L and see the result!

Yes, the slides will be displayed in random order - nothing you can do about that :(

Thursday, July 27, 2017

Perl Insert Contents of One File Into Another at Line Matching Regex

Nice to have something I think is better than stackexchange - how often does that happen :) ?

To insert after a line matching the regex

perl -n -i -e 'print; print `cat FILE_TO_INSERT` if m#REGEX_TO_MATCH#; ' FILE_TO_MODIFY

To insert before :

perl -n -i -e 'print `cat FILE_TO_INSERT` if m#REGEX_TO_MATCH#; print;' FILE_TO_MODIFY

If you want the insertion to happen at the first match ONLY :

perl -n -i -e 'print `cat FILE_TO_INSERT` if m?REGEX_TO_MATCH?; print;' FILE_TO_MODIFY

A very valid question is, what do you do if your match pattern has the question-mark character? :)

https://unix.stackexchange.com/questions/32908/how-to-insert-the-content-of-a-file-into-another-file-before-a-pattern-marker

Saturday, July 08, 2017

A (Relatively) Low IQ Not Apparent in a Prepared Speech

Man, what a nice speech - he's succinctly put all 3 things together - Versailles > War > Lebensraum > the problem necessitating the formation of NATO. One thing missing is the human emotions that caused WW1 to happen in 1914 in the first place. When is being swollen-headed a crime? When is it a crime to want your own "place in the sun"? Is military-posturing a crime against peace if it is likely to lead to war? And he conveniently leaves out his role in the Final Solution as well.

Herr Ribbentrop :

This Trial will go down in history as a model example of how, while appealing to hitherto unknown legal formulas and the spirit of fairness, one can evade the cardinal problems of 25 years of the gravest human history.

If the roots of our trouble lie in the Treaty of Versailles--and they do lie there--was it really to the purpose to prevent a discussion about a treaty which the intelligent men even among its authors had characterized as the source of future trouble, while the wisest were already predicting from which of the faults of Versailles a new world war would arise?

I have devoted more than twenty years of my life to the elimination of this evil, with the result that foreign statesmen who know about this today write in their affidavits that they did not believe me. They ought to have written that in the interests of their own country they were not prepared to believe me. I am held responsible for the conduct of a foreign policy which was determined by another. I knew only this much of it, that it never concerned itself with plans of a world domination, but rather, for example, with the elimination of the consequences of Versailles and with the food problems of the German people.

If I deny that this German foreign policy planned and prepared for a war of aggression, that is not an excuse on my part. The truth of this is proved by the strength that we developed in the course of the second World War and the fact how weak we were at the beginning of this war.

History will believe us when I say that we would have prepared a war of aggression immeasurably better if we had actually intended one. What we intended was to look after our elementary necessities of life, in the same way that England looked after her own interests in order to make one-fifth of the world subject to her, and in the same way that the United States brought an entire continent and Russia brought the largest inland territory of the world under their hegemony. The only difference between the policies of these countries as compared with ours is that we demanded parcels of land such as Danzig and the Corridor which were taken from us against all rights, whereas the other powers are accustomed to thinking only in terms of continents.

Before the establishment of the Charter of this Tribunal, even the signatory powers of the London Agreement mast have had different views about international law and policy than they have today. When I went to see Marshal Stalin in Moscow in 1939, he did not discuss with me the possibility of a peaceful settlement of the German Polish conflict within the framework of the Kellogg-Briand Pact; but rather he hinted that if in addition to half of Poland and the Baltic countries he did not receive Lithuania and the harbor of Libau, I might as well return home.

In 1939 the waging of war was obviously not yet regarded as an international crime against peace, otherwise I could not explain Stalin's telegram at the conclusion of the Polish campaign, which read, I quote:

"The friendship of Germany and the Soviet Union, based on the blood which they have shed together, has every prospect of being a firm and lasting one."

Here I should like to emphasize and stress the fact that even I ardently desired this friendship at that time. Of this friendship there remains today only the primary problem for Europe and the world: Will Asia dominate Europe, or will the Western Powers be able to stem or even push back the influence of the Soviets at the Elbe, at the Adriatic coast, and at the Dardanelles?

In other words, practically speaking: Great Britain and the United States today face the same dilemma as Germany faced at the time when I was carrying on negotiations with Russia. For my country's sake I hope with all my heart that they may be more successful in their results.


Wednesday, June 28, 2017

Jordan Sissel Kennt Nicht Seine Eigene Tool

he says :

Example: Send ctrl+c to all windows matching title 'gdb' (See COMMAND CHAINING) xdotool search --name gdb key ctrl+c

But that doesn't work - no sir.

Fortunately, 

xdotool windowactivate `xdotool search --name gdb` ; xdotool key ctrl+c

Works, by the power of G!!

Kudos :

Saturday, June 17, 2017

Schooled in Efficient Code - by Udacity

Take a sudoku grid and implement the only-choice - that is, when you have multiple choices for numbers to put in a square - when one of those choices occurs only in this square, you know what to do..

My answer :

    for box in unit :
        for choice in grid[box] :
            others = ''.join( [ grid[x] for x in unit if not x == box ] )
            if not re.search( choice , others ) :
                grid[box] = choice

And U :

    for digit in '123456789':
         dplaces = [box for box in unit if digit in values[box]]
         if len(dplaces) == 1:
             values[dplaces[0]] = digit

For each number in 1..9, they get the boxes that contain that number and then, when there's only one box for a particular number, they assign that number to that box - yes, you'll be doing some redundant work, but ain't the code short and sweet?

Look at me - I first get a string made up of the contents of all the other boxes and then I check if this box's contents (one number at a time) occur in that string..

Wednesday, May 17, 2017

The Underwhelming Genius of Guido van Rossum

or whoever coded the regex engine.. Why can't they just try to be as good as Perl?

re.match( pat, string)

pat = '('

gets :

error: error( 'u...thesis',)

WT*? Have these guys never heard of abort, retry, fail?

Thursday, May 04, 2017

Microsoft Excel : How to Put Thumbs Up Down Symbols

Does it involve conditional formatting?  YES

Is this super easy? NO - it's EASY but not SUPER easy - you unfortunately have to jump through a couple of hoops. You would think they would have included Thumbs Up and Thumbs Down in their Icon Sets, but, that's M$ for you :)

========================================

1. The column of interest - you will have to enter capital C where you want the Thumps Up, Capital D for Thumbs Down - no way around this.

2. In the top-most cell, enter a C and change the font from the default to Wingdings. You'll see the C change to a Thumps Up.

3. Make it bold and Green font if you wish and change the font size if you wish. Done? Drag through all rows

4. Now, with all rows of this column selected, assuming the top-most (not header) cell is E3, go to Conditional Formatting and choose New Rule


5. Now, enter this formula (adjust the E3 to what it needs to be in your case - the coordinates of the top-most data cell in your table)


6. Set the Format to what you need - probably Red since Green would be for Thumbs Up.

That's it, enjoy..


Thursday, April 27, 2017

Alan Skorkin's Treasure Trove (Bash Shortcuts)

http://www.skorks.com/2009/09/bash-shortcuts-for-maximum-productivity/

The ones I didn't know about :

Ctrl + k - delete from cursor to end of command line
Ctrl + u - delete from cursor to start of command line
Ctrl + w - delete backwards one word
Ctrl + y - paste text victimized by most recent deletion
Ctrl + xx - move between start of command line and current cursor position
Alt + b/f - back/forward one word
Alt + d - delete to end of word
Alt + c - capitalize start of word and go to end of word
Alt + u - make uppercase from cursor to end of word
Alt + l - make lowercase from cursor to end of word
Alt + t - swap current word with previous (SO COOL!)
Alt + . - insert last word of previous command

!blah:p - print out the command that !blah would run and add it to history
!* - previous command except for the FIRST word (even geniuses get it wrong sometimes :)
!!:s/foo/bar - execute previous command by replacing foo with bar

And, nuggets from Linux Foundation's EDX course : http://tersamgt.blogspot.com/2015/01/almost-20-years-with-unix-mann-kann.html

Wednesday, April 26, 2017

Life's Tough : Out of the Blue Git-bash Can't Find Python

Must be ransomware. Just like that PC turns off last night and now, can't get Python action in Git bash. What gives?

All history gone too.. scary

Thursday, April 20, 2017

The Kofman Gap

Nice :

Conscious employees take responsibility for their life. They don't compromise human values for material success. They speak the truth and listen to others’ truth with honesty and respect. They look for Creative Solutions to disagreements and honor their commitments impeccably. They are in touch with their emotions and express them productively.

Unconscious employees do the opposite. They blame others for problems, seek immediate gratification regardless of ethics and claim to be always right. They hide significant information, sweep conflicts under the table and negotiate to beat their opponents. They expect to get what they need without asking, make irresponsible promises and don't honor their commitments. They repress their emotions or explode irrationally.

Conscious employees require conscious managers if they are to fully commit their energy to organizational goals. Unless they feel acknowledged, supported, and challenged by their managers, conscious employees will withdraw.

-- couldn't have put it better.

Not nice :

How to deal with unconscious employees? How do you push them out in a nice way? 



Thursday, April 13, 2017

Daily Learning :) Cool Websites

  1. 10-minute-email - when you need something just to subscribe to something :)
  2. Madeon's Adventure Machine - make your own techno!
  3. Camel Camel Camel - AMZN price history
  4. Hacker typer - impress friends :) ( a prank )
  5. Hike Mt. Everest in 3D
  6. Down for everyone (a website) or just me?

Friday, April 07, 2017

Gems from Ashlee Vance

Musk has taken industries like aerospace and automotive that America seemed to have given up on and recast them as something new and fantastic. At the heart of this transformation are Musk's skills as a software maker and his ability to apply them to machines. He's merged atoms and bits in ways that few people thought possible, and the results have been spectacular.

Okay, I thought that was good, until I read :

(oh, thanks to Omkar Pawaskar, you can read for free without Vance getting richer :) :

While Musk had exceled as a self-taught coder, his skills weren’tnearly as polished as those of the new hires. They took one look atZip2’s code and began rewriting the vast majority of the software.Musk bristled at some of their changes, but the computer scientistsneeded just a fraction of the lines of code that Musk used to get their jobs done. They had a knack for dividing software projects intochunks that could be altered and refined whereas Musk fell into theclassic self-taught coder trap of writing what developers callhairballs—big, monolithic hunks of code that could go berserk formysterious reasons.

Sunday, March 26, 2017

Handy Perl for Tax Time

Convert

1/15/15 Bought 10 MXL MAXLINEAR INC $14.38 4.95 164.2
1/2/16 Bought 60 MXL MAXLINEAR INC $14.38 4.95 724
3/2/2016 Sold -52 MXL MAXLINEAR INC $17.14 4.95 $0.03 $886.31

to

3/2/2016 MXL 70 886.31 various 888.2

You'll generate a bunch of these I hope and later put the column headings on - in Excel :

sell-date, ticker, quantity, proceeds, buy-date, cost-basis...... profit/loss easy to do in Excel..

Use :

#!/usr/bin/perl -w

open( INFO, "$source");

$cost = 0;
$sale = 0;
$qty = 0;
$buy_d = '';

while( ){
 /^\s*(\S+)\s+(\S+)\D+(\d+)\s+(\S+).+\s+\(?\$?([^\s)]+)\)?\h*\r?$/; $type = $2; $date = $1; $q = $3; $tick = $4; $total = $5; $total =~ s/,//g; if( $type =~ /bought/i ){ $qty += $q; $cost += abs( $total ); unless( 'various' eq $buy_d ){ if( '' eq $buy_d ){ $buy_d = $date; } else{ $buy_d = 'various'; } } } else { $sale += abs( $total ); $sell_d = $date;
  $sell_q = $q;
}
print; } $cost = $cost*$sell_q/$qty; print "\n$sell_d,$tick,$sell_q,$sale,$buy_d,$cost\n";

The astute reader will notice that I'm dumping a CSV line - so you could just pipe through perl -p -e 's/,/ /g;' - which will of course mess up the original - but who cares :) CSV's are more useful in Excel..

Saturday, March 25, 2017

Python is Crap Compared to Perl

When it comes to text processing.

Okay, this is a known fact. Question - why hasn't this gotten more attention?

How would you do this?

string : "Mary had a little lamb1" --> "Mary had1 a little lamb" . Okay, a lame example - I want to append a 1 after a d or a b. In perl, it's as simple as s/([db])/${1}1/g . What is it in Python????

Here's a guy who barely scratches the surface. A valiant attempt though .. better half a loaf.

What is the equivalent of using curly braces for variable names within interpolated strings?????

Anyways, here's one way of accomplishing this particular task (Thanks!) :

re.sub( r"(?P)[db])" , r"\g1" , myString )

Enjoy..