Skip to content

Instantly share code, notes, and snippets.

@tra38
Last active January 10, 2023 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tra38/5049778d7564b03e6dbc78dd4a1402b2 to your computer and use it in GitHub Desktop.
Save tra38/5049778d7564b03e6dbc78dd4a1402b2 to your computer and use it in GitHub Desktop.

Dear StackOverflow, I want to install nokogiri on my Mac OSX machine, but the native extensions are failing to build...what should I type in instead?

gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/usr/local/opt/libxml2/include/libxml2

Source: http://stackoverflow.com/a/25068003/4765379

But StackOverflow, now nokogiri is raising a warning!

WARNING: Nokogiri was built against LibXML version 2.9.3, but has dynamically loaded 2.9.4

Eh, worry about it later.

How do I destroy the Postgres database on Heroku?

heroku pg:reset DATABASE_URL --confirm nameofapp

Source: http://stackoverflow.com/a/24726013/4765379

Oh Stacky, when I typed in rails console on the command line, I get an error about Rails not finding the readline.bundle image. Er...what's an image?

sighs

ln -s /usr/local/opt/readline/lib/libreadline.7.0.dylib /usr/local/opt/readline/lib/libreadline.6.dylib

Source: rails/rails#26658 (comment)

CKEditor works on my machine! But it's not working in production.

galetahub/ckeditor#307

TypeError: no implicit conversion of nil into String. utils.rb:24:in quote_ident. What's going on?

Let's wait until tomorrow and just ask the White Sheep.

My billion-dollar Rails app uses Postgres as a database. But it's not running locally because it "could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?"

The database is off silly, turn it on!

But I can't turn the database on. When I try to do so, it's complaining about a stale postmaster.pid file...

rm /Users/<user_name>/Library/Application Support/Postgres/var-9.6/postmaster.pid

Source

I accidentally pushed a branch up to a remote git repoistory that honestly, should not have been pushed up. How do I delete this branch?

git push origin :branch_name

I want to push to "heroku master" a branch that isn't actually master locally. How do I do that?

git push heroku your_branch:master

An error occurred while installing json (1.8.3), and Bundler cannot continue. Make sure that gem install json -v '1.8.3' succeeds before bundling.

sudo apt-get install libgmp-dev

But I'm on MacOSX!

Oh. Then add this to your Gemfile:

gem 'json', github: 'flori/json', branch: 'v1.8'

Source

I want to have a staging Heroku remote and a production Heroku remote. How do I get it to work?

Painfully.

By default, the heroku command operates on the application referred to by the heroku Git remote. This is great for simple apps, but starts to break down when you need multiple Heroku apps to serve up different environments (staging, production, and so on). You end up having to set up a bunch of remotes by hand, and then your reward is the eternal obligation to explicitly pass in the remote: heroku run console -r staging and the like.

My solution to this problem is twofold:

  1. Create a binstub for each Heroku app.
  1. Use this plugin, which encapsulates common operations on the Git remote.---Heroku Remote README

Another Gist About the Deployment Process

I'm either upgrading an existing Rails application to 5.x or creating a brand new Rails 5.x application. How do I avoid accidentally using ActionCable?

http://blog.sundaycoding.com/blog/2016/08/10/how-to-remove-action-cable-from-a-rails-app/

I want to use Ruby to convert a DateString to a human-readable Date format, without dealing with strftime.

require 'date'
def convert(date_string)
  date_object = DateTime.parse(date_string)
  "#{date_object.month}-#{date_object.day}-#{date_object.year} (#{date_object.hour}:#{date_object.min}:#{date_object.sec})"
end

How do I set up a docker-machine on MacOSX?

First, install the docker stuff.

brew install docker-compose

Then, set up a machine and export its settings over to your terminal shell...

docker-machine create default
eval "$(docker-machine env default)"

How do I view a web app that is hosted on my "default" docker-machine?

docker-machine ip default to get the IP address. Then copy and paste that into the address bar, followed by :PORT_NUMBER.

Example: http://192.168.99.100:8000/

I want to do local tunneling for my webapp using lt (installed via npm), but I'll need to actually forward the local tunneling over to a different server (example: a docker instance), and not on my actual localhost?

For the sake of argument, let assume that the site we want to redirect users to is http://192.168.99.100:8000/

lt -l 192.168.99.100 -p 8000

DOCKER! I typed in docker compose up to start up my web server hosted in the default machine and then Docker complained, stating ERROR: Couldn't connect to Docker daemon - you might need to run `docker-machine start default`. DOCKER!

docker-machine start default
eval "$(docker-machine env default)"
docker-compose up

I want to deploy my create-react-app application onto GitHub Pages, but doesn't want to create a new branch called gh-pages. Instead, I want to have the generated static site be on the same branch as the source code. GitHub Pages has the ability to read from the /docs folder...how can we exploit that 'feature'?

Here's how you do it.

How do I convert [1,2,3,4,5,6] into [[1,2,3],[4,5,6]] in Javascript? I know you can do this in Ruby using Enumerable#each_slice, but Javascript seem like a different beast.

function chunks(array, chunk_size) {
  var outputArray = [];
  while (array.length > 0)
    outputArray.push(array.splice(0, chunk_size));
  return outputArray;
}

console.log(chunks([1,2,3,4,5,6], 3))

Source

The MARKDOWN QUERY

"Okay, Stacky, this is a serious issue, when I write code like this in Gitbook:

1. Awesome Text

- Clarification


2. More Awesome Text

It renders like this:

  1. Awesome Text
  • Clarification
  1. More Awesome Text

The code renders fine in Github-Flavored Markdown, but I'm talking about Gitbook-Flavored Markdown...so...yeah...

What should I do?"

The answer comes from https://meta.stackoverflow.com/questions/143256/quotes-override-list-item-numbers

1\. Awesome Text

- Clarification


2\. More Awesome Text

It renders like so:

1. Awesome Text

  • Clarification

2. More Awesome Text

Whenever I make a change in a single JS file, I receive a completely unrelated "Runtime Error" that prevents the JS file from executing. For example, I may make changes in Line 112 to Line 124, but the Runtime Error is referring to Line 287...

Look at the code that you are modifying. Most likely, you wrote a typo in your code which makes the whole file malformed. JS will not inform you of this, but still attempts to interpret your file. As for the exact behavior that leads to the Runtime Error, I don't know yet and I may have to look that up in the future. I do know how to fix it.

I want to install random-python-package using pip, but when pip attempts to uninstall the old version of random-python-package, it throws an error: [Errno 1] Operation not permitted. What do I do, Stacky?

pip install --user random-python-package

How do I enter into bash mode on a Docker container so that I can run commands?

docker-compose run web bash

I want to customize the behavior of \b in Regex.

You can't. You can, however, create your own word-boundary Regex fairly easily, according to the guide Regex Boundaries. If you are a fan of StackOverflow, search for exclude some characters from word boundary to find other ways of hand-generating your own word-boundary regex.

When trying to install the python package secp256k1, I received an error: Failed building wheel for secp256k1. So tell me, how do I invent the wheel?

Install all the build tools for secp256k1, and then try again. This should work.

How do I make my bash script script.sh executable?

chmod +x script.sh

I want to do a benchmark quickly of some Python code. What's the best way of doing that?

import timeit
import pdb

start_time = timeit.default_timer()

print("HELLO WORLD")

elapsed = timeit.default_timer() - start_time

pdb.set_trace()

When I type in su, it asks me for my password. I gloriously type it in and then it said su: Sorry. How do I handle it?

sudo su, then type in your password. Then you'll raise your permission to superuser status.

I like to lock up a file on MacOSX (and then unlock that file) on demand! I know I have to use chflags but can you give me a brief tutorial on how to use it?

Here's an example where I prevent people from changing a file...

sudo chflags uchg file.md

And then, when I want to allow people to change the file afterwards...

sudo chflags nouchg file.md

What is a good checklist for deciding whether to refactor something?

Here's a good checklist.

I have a passion for unit-testing the output of a function that prints to a console, like (Console.WriteLine)? Could you help me fufill this passion of mine by showing me a code snippet where this can be done in C#?

Fair warning - this code is under the Code Project Open License, which is not considered an open-source license (due to its clause on restricting people from doing "illegal, immoral, or improper" uses).

From https://www.codeproject.com/articles/501610/getting-console-output-within-a-unit-test:

The Code

using System;

namespace ConsoleLogger
{
    public class DummyClass
    {
        public void WriteToConsole(string text)
        {
            Console.Write(text);
        }
    }
}

The Helper Class

using System;
using System.IO;

namespace ConsoleLogger.Tests
{
    public class ConsoleOutput : IDisposable
    {
        private StringWriter stringWriter;
        private TextWriter originalOutput;

        public ConsoleOutput()
        {
            stringWriter = new StringWriter();
            originalOutput = Console.Out;
            Console.SetOut(stringWriter);
        }

        public string GetOuput()
        {
            return stringWriter.ToString();
        }

        public void Dispose()
        {
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }
    }
    
    
}

The Unit Test

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ConsoleLogger.Tests
{
    [TestClass]
    public class DummyClassTest
    {
        [TestMethod]
        public void WriteToConsoleTest()
        {
            var currentConsoleOut = Console.Out;

            DummyClass target = new DummyClass(); 
            
            string text = "Hello";

            using (var consoleOutput = new ConsoleOutput())
            {
                target.WriteToConsole(text);

                Assert.AreEqual(text, consoleOutput.GetOuput());
            }

            Assert.AreEqual(currentConsoleOut, Console.Out);
        }
    }
}

On April Fools 2018, Stack Overflow released "Quack Overflow". I want to use this feature for my own, uh, rubber-duck debugging. How would I do that?

Here's a mirror of Quack Overflow (with noise): https://unikong.github.io/quackoverflow/

Here's a GIF of Quack Overflow (w/o noise): http://tra38.github.io/quack_overflow.gif

Program A is under the GPL license. I am building "Program B", and I want to use Program A as a dependency. But I don't want to license "Program B" under the GPL itself. What do I need to do to handle this specific issue?

Link to Stack Overflow Answer, by MadHatter

I want to use howdoi on any machine that has Internet access. How can I do that?

Use https://repl.it/@tra38/LittleNiftySubweb .

How do I find the location of the command-line tool example-tool?

On a Windows machine (Windows Server 2003 and later), use where:

where example-tool

On a Linux/MacOSX machine, use which:

which example-tool

How do I raise an application error in an Oracle PL/SQL stored procedure that contains valuable debug information?

raise_application_error(-20101,CONCAT('Hello world! Here's some useful debug info:', debug_information))

In Oracle PL/SQL, what is the difference between DBMS_UTILITY.FORMAT_ERROR_BACKTRACE and DBMS_UTILITY.FORMAT_ERROR_STACK?

FORMAT_ERROR_STACK shows the full error message, while FORMAT_ERROR_BACKTRACE shows the line numbers where errors had been raised (allowing you to know where the error occurred). You can get both information (error message and backtrace) if you don't handle the exception properly (though that is probably not good practice).

For more information, please read PL/SQL: Tracing Lines.

I'm using the smarter_csv Ruby gem and running the command SmarterCSV.process("exampel.csv"). Yet I'm getting the following error:

/Users/<user_name>/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/smarter_csv-1.2.3/lib/smarter_csv/smarter_csv.rb:244:in `ensure in process': undefined method `close' for nil:NilClass

You are getting that error because you mistyped the file name that you're trying to read (it's supposed to be example.csv), so SmarterCSV is trying to fnd a file that doesn't exist. And we haven't told SmarterCSV what to do next if it can't find the file, so it throws an error. Fix the typo and try again.

Python's JSON library is throwing an error: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 39 column 3

Look at the JSON blob that you're trying to parse.

{
   "name": "JSON Blob",
   "interests": "cooking",
   "bio": "in progress",
}

That dangling comma after "in progress" seems to be a hint to our decoder that there's a "property" that needs to be parsed (which implies the existence of a property name). So the JSON library is looking for it. But, of course, there is no property, just a dangling comma, so the JSON library throws an error. Delete the dangling comma, and the error should go away.

I have scheduled Windows Task Manager to run a very awesome .exe file every day. It claims to have successfully executed the task, but I doubt that it's actually doing anything.

  1. Check to see if it is a permissions issue:

★ Answer from https://stackoverflow.com/questions/7733765/windows-task-scheduler-running-application-but-cannot-send-email ★ This is a permissions error, the user you're running the task as when running through the console will have more permissions than the user running the task. It appears the PDF app you are using is trying to write to a temp file or similar and it doesn't have permissions. (I'm assuming the email has a PDF attachment or similar that is being generated on the fly) If you made your task run as an administrator that should work, you could then run it as a more restricted user and work out which permissions to apply to where to lock it down.

★ Answer from https://stackoverflow.com/questions/20744604/no-permission-to-write-a-file-from-task-scheduler ★ There may be quite a few reasons of it, first check below points: Check whether the user who has scheduled batch script to run in Task scheduler has admin access on the system or not. Give that user full Share/NTFS permissions on the "RedirectedFolders" and all of the sub folders as well.you can manually propagate all permissions down to the folders. The user should have read and write permissions along with full control to the "RedirectedFolders" .

  1. Make sure that you are using absolute paths instead of relative paths in the source code or configuration files of the .exe file:

★ Answer from https://stackoverflow.com/questions/26302687/python-wont-run-with-task-scheduler-but-will-run-normally ★ Make sure that you are using absolute paths in your program, and not relative ones. Task Scheduler is probably running your program from a different directory, and if you have relative paths in your program it is not able to find them. One easy way around this is to put the following line at the top of your program (assuming you've already imported os): os.chdir("c:/Users/User/Documents/Python/Test/Client") Now, all the commands below are being run from this directory, and relative paths should work.

★ Answer from https://stackoverflow.com/questions/665014/my-script-wont-run-under-the-task-scheduler-why ★ I had a similar problem running a scheduled task on my SVN server. My script was writing to what I thought was the current working directory (the directory I specified for the task as the "Start in" folder). If I logged onto the server and ran the script it worked fine. When running as a scheduled job it wouldn't. In my case, it looked like the scheduler re-assigned the working directory to be the directory specified in the TEMP environment variable for the user account used to run the job, not the directory I specified for the task (the "Start in" folder). Check the TEMP folder for the account and see if your files are there.

I scheduled Windows Task Manager to run a C# program regularly, but that C# program is crashing! What can I do to get the exception message?

★ Answer from https://stackoverflow.com/questions/14711633/my-c-sharp-application-is-returning-0xe0434352-to-windows-task-scheduler-but-it ★ Another option is to simply use the Application log accessible via the Windows Event Viewer. The .Net error will be recorded to the Application log.

I love browsing the web using curl, but I don't like seeing all those HTML tags! How do I strip them out?

★ Answer from https://stackoverflow.com/questions/35777319/extract-the-source-of-the-webpage-without-tags-using-bash ★ You can pipe to a simple sed command :

curl www.gnu.org | sed 's/<\/*[^>]*>//g'

Give me a quick code snippet for pluralizing a random English word.

require 'calyx'
VOWELS = ['a', 'e', 'i', 'o', 'u']
  
grammar = Calyx::Grammar.new do
  #https://github.com/galaxykate/tracery/blob/70f69ed5386371fdb9108cfbd21c0df5afc23b42/js/tracery/mods-eng-basic.js#L76
  filter :pluralize do |input|
    last_character = input[-1].downcase
    rest_of_string = input[0..-2]
    case last_character
    when 's'
      plural_ending = "es"
    when "h"
      plural_ending = "es"
    when "x"
      plural_ending = "es"
    when "y"
      if VOWELS.include?(rest_of_characters[-1])
        plural_ending = "ies"
      else
        plural_ending = "s"
      end
    else
      plural_ending = "s"
    end
    "#{input}#{plural_ending}"
  end
  
  start "{word.pluralize}"
end

puts grammar.generate(word: "cat")

When I used the calyx Ruby gem, I got the following error: undefined method `evaluate' for nil:NilClass (NoMethodError). Why did I get that?

You wrote something like this:

rule_1 rule_2, rule_3

...when you should have instead written the code like this to indicate to Calyx you are trying to do rule indirection:

rule_1 :rule_2, :rule_3

When using the calyx Ruby gem, how do I dynamically change the rules?

class AppGreeting < Calyx::Grammar
  start 'Hi {username}!', 'Welcome back {username}...', 'Hola {username}'
end

greeting = AppGreeting.new

human_context = {
  "username": ["Alice", "Bob", "Eve", "David"]
}

puts greeting.generate(human_context)

world_context = {
    "username": "{world_phrase}",
    "world_phrase": ['{happy_adj} world', '{sad_adj} world', 'world'],
    "happy_adj": ['wonderful', 'amazing', 'bright', 'beautiful'],
    "sad_adj": ['cruel', 'miserable']
}

puts greeting.generate(world_context)

alice_context = {
    "username": "Alice"
}

puts greeting.generate(alice_context)

Note that if a rule is already defined, you cannot "redefine" it - so you must define your rule once (either within the Calyx grammar or within the context map). If you attempt to "redefine" a rule, an exception is raised:

grammar_context = {
   "start": "grammar deleted for security reasons"
}

puts greeting.generate(grammar_context)
# Calyx::Errors::DuplicateRule (:start is already registered)

How do you create a procedural text generator that produces "reproducible" outputs? (After all, humans like to re-read the same work multiple times...)

There's multiple options, each with pros and cons.

  1. Inject your random generator with a "reproducible" seed. If you want the same output, just reuse the same seed.
Calyx::Grammar.new(seed: sum) do
  # grammar here
end

Pros: Easy to pull off.

Cons: Not extensible - you cannot change the grammar without changing all the generated outputs.

  1. Follow No Man's Sky's approach to maintanable procedural generation (slides here, scroll down to "Moving Parts: Problem Solving For Updatable Procedural Generation"). It appears they're using two approaches:
  • "seed trees" instead of a single generator, so you can modify one branch of the tree without drastically changing the output
  • Fixed-sized tables (so when you're adding new content, you can simply "reassign part of the range", without changing the rest of the generated output)

Pros: Incredibly maintanable (in the long term), changes are less noticable

Cons: Extremely complicated to set up. May not be practical for throwaway text generation projects.

  1. Saving the generated output into a database (and then giving people limited access the database if they want to recover the generated output).

Pros: ?

Cons: Require you to set up a database. Also requires you to set up an API (and even a webapp) to allow users to interact with the database.

  1. Saving the generated output into a URL and requiring people to visit that URL if they want to recover the generated output. (Example: itty.bitty.site)
require 'base64'
require 'lzma'
require_relative 'lib/text_generator.rb'

generated_text = TextGenerator.generate

compressed = LZMA.compress(generated_text)

base64page = Base64.encode64(compressed).gsub("\n","")

generated_url = "https://itty.bitty.site/#/?#{base64page}"

Pros: Fairly easy to pull off (though slightly more difficult than Option #1). No maintanance needed after the URL is generated.

Cons: Users still have to manually save the URL somewhere for later use. Requires an external webapp to "decode" the URL. Technology is still experimental, and IE11/Edge does not provide support to "URL applications" yet.

  1. Tell users just to copy and paste the generated output into a text file.

Pros: Easiest option for the programmer. (The best code is no code at all!)

Cons: Annoy users.

  1. Keep around all major versions of your code, and provide a "major version number" that users must provide along with the seed. We will use this version number (and the seed) to generate the output.

Pros: Most effective at perserving all possible generated outputs (since the user has access to all major generators).

Cons: Extreme complexity and maintenance burden for very little benefit.

How do I patch a Git Repo?

From https://stackoverflow.com/a/28193089 (a coworker showed me this link)

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

Download the patch into your repo and then run git apply mypatch.patch

In Visual Studio 2010, sometimes, if you build the solution in both Debug and Release mode, you'll get an error message about duplicate Tests existing. How do I deal with this?

Clean both solutions and then build the solution in the mode you want. (There is an SO post that explains this but I forgot what it was, so as soon as I find it, I'll update this section.)

What is the difference between prefix (++x) and postfix (x++)?

Prefix - Increment the variable, then use the value in the variable

z = 3
x = ++z
console.log(x) //4
console.log(z) //4

Postfix - Use the value in the variable, then increment the variable

z = 3
x = z++
console.log(x) //3
console.log(z) //4

The ++ is the increment operator, while -- is the decrement operator.

In Ruby, how do I turn a "string" into an integer?

require 'digest'

word = gets.chomp

hexdigest = Digest::SHA256.hexdigest(word)

# Convert the digest to a "Base 16" integer
integer = hexdigest.to_i(16)

How do I generate a random phrase using Ruby?

Lots of answers on StackOverflow, but this gist has a RandomString module that could be useful. The command I like the most from that module is...

RandomString.by_sample

If you don't want to copy and paste a whole module, then just use this method instead...

def random_string(length = 8)
  chars = [*'a'..'z', *'A'..'Z', *0..9]
  [].fill(0, length) { chars.sample }.join
end

How do I do pagination in Ruby?

Use the tty-pager gem.

require 'tty-pager'

pager = TTY::Pager.new
pager.page("Very long text...")

How do I require Ruby gems on repl.it?

You need to use bundler/inline to install the Ruby gems.

require 'bundler/inline'

gemfile true do
 source 'http://rubygems.org'
 gem "calyx", '>=0.18.0'

 gem "ruby-lzma"

 gem "redcarpet"

 gem 'progressbar'
end

Then you can require the Ruby gems as normal.

Tutorials:

I got this weird error in Calyx...undefined method evaluate for nil:NilClass?

/Users/<user_name>/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/calyx-0.18.0/lib/calyx/production/choices.rb:49:in `evaluate': undefined method `evaluate' for nil:NilClass (NoMethodError)

You probably had this code in the system:

start '{awesome_rule}'

awesome_rule

really_awesome_rule '1', '2', '3'

We need to randomly select a string from awesome_rule, but awesome_rule is blank, so we throw an error.

Does Visual Studio work on Mac OSX?

Of course! Go to visualstudio.com today and download it. Now you can cheerfuly use Microsoft products on non-Microsoft machines!

What is a closure in C#?

Read this - https://www.simplethread.com/c-closures-explained/

This code snippet (from the blog post) should also help...

static void Main(string[] args)
{
    var inc = GetAFunc();
    Console.WriteLine(inc(5)); # 7
    Console.WriteLine(inc(6)); # 9
}

public static Func<int,int> GetAFunc()
{
    var myVar = 1;
    Func<int, int> inc = delegate(int var1)
                            {
                                myVar = myVar + 1;
                                return var1 + myVar;
                            };
    return inc;
}

myVar is a free variable that is now bound to the delegate function. ("A free variable just happens to be a variable which is referenced in a function which is not a parameter of the function or a local variable of the function.")

  • Closures are useful because they allow us to create functions that can store "state" (and behind the scenes, this "delegate" is actually a class with both behavior and state...it's just syntatic sugar that causes it to look like a function).

A closure contains behavior and state...but a class also contains behavior and class as well. Wait, what's the difference between a closure and a class, if they both contains behavior and state?

Nothing. Anything you can do with a class, you can do with a closure. But there may be instances where a closure may be better than a class, and vice versa.

For example...in https://www.simplethread.com/c-closures-explained/, Bob posted a useful closure function:

private static Func accumulate(int n)
{
  return i => n += i;
}

Now, you could easily do this same thing within a class, but it's a lot more complicated code. So in this scenario, use a closure. Use the best tool for the job.

You can also look at this StackOverflow link - https://stackoverflow.com/questions/2497801/closures-are-poor-mans-objects-and-vice-versa-what-does-this-mean

What are the different ways of redirecting someone to another site using JavaScript?

  • location="https://example.com";: Only really useful for code-golfing. [Richard Duerr](https://stackoverflow.com/questions/4744751/how-do-i-redirect-with-javascript#comment67373459_39677714] said "I would avoid this, because under certain circumstances, the variable "location" isn't available, and could be created as global. Plus, if the programmer mistypes it slightly, they create a new global. It's much better to be verbose."
  • window.location = "https://example.com";: Ensures that we are changing the correct location global variable. phpvillian suggests another variant: "window.location.href = "example"; is probably better practice because browser policies might restrict its use and block it since .location and .location.href are not exactly the same. However in some cases using .location is ideal particularly if you're using same origin policies like an iframe."
  • window.location.replace(https://example.com) - According to sidanmor: "Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco."

sidanmor's Grand Advice:

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

How do I change directories in Google Collab? If I use the !cd new_directory/ symbol, it will spin up a new subshell and change directory within that subshell before destroying it...the main shell itself won't change directories...

Use %cd new_directory (if you want to stick to using bash) or os.chdir('new_directory') (if you really want to use Python). For more info, read this Stackoverflow question.

Breakpoints are not being loaded in Visual Studio. How do I fix this?

From StackOverflow, a community wiki post:

First try rebuilding your project by right mouse click the project > Rebuild If that doesn't work, try a clean of the project (right mouse click on the project > clean)

If that didn't work check this:

1. Right mouse click your project
2. Select [Properties]
3. Select the [Build] tab
4. Make sure [Define DEBUG constant] and [Define TRACE constant] are checked
5. Make sure [Optimize Code] is unchecked
6. Click the [Advanced] button at the bottom of the Build tabpage
7. Make sure that [Debug Info:] is set to [full]
8. Click [OK] and rebuild the project ;-)

(step 6 generates the .pdb files, these are the debugging symbols)

"Compiler complains about unassigned variable after switch on enum" (use of unassigned local variable)

Source

Buggy Code:

string str;
Foo foo = Foo.Bar;

switch (foo)
{
    case Foo.Bar: str = "a"; break;
    case Foo.Baz: str = "b"; break;
}

str.ToLower();

Error:

use of unassigned local variable 'str'

You're getting this error because it's possible to bypass that switch statement entirely (for example, you could assign foo to be Foo.Bat or do something like (Foo)1234), thereby ensuring that str might not be assigned. To fix this error, make sure that you handle all possible cases, thereby ensuring that nobody could bypass the switch statement.

Solution:

switch (foo)
{
    case Foo.Bar: str = "a"; break;
    case Foo.Baz: str = "b"; break;
    default: Debug.Assert(false, "An enum value is not covered by switch: "+foo);
}

I have forgotten my "Restrictions"/"Screen time Passcode" for my iOS device and want to recover it. I also want to use open-source tools to conduct this recovery. What do I need to do?

  1. Create an backup of your iOS device using the open-source tool libimobildevice. (License is LGPL 2.1)
  • Since iOS 12, the backup must be encrypted (otherwise your Restrictions/Screen Time Passcode would be excluded from the backup).
  1. Extract the Restrictions/Screen Time Passcode using Pinfinder. (License is MIT)
  • By default, Pinfinder will look for your backups in /Users//Library/Application Support/MobileSync/Backup . You can pass in a command-line prompt to scan within a specific folder - however, if you are having difficulties, just copy+paste your backup into the default folder.

How do I use Windows programs on a MacOSX machine?

Use Wine. Here's a tutorial.

To install Wine using homebrew, type: brew cask install wine-stable

To run any Windows programs/installer, type: wine program.exe

What is the difference between Camel Case, Pascal Case, Snake Case, and Kebab case? And why do these cases exist?

camelCase
PascalCase
snake_case
kebab-case

These types of cases exist because in almost all programming languages, we cannot use spaces when declaring variables. So how do you name a variable that contains multiple words, if you cannot use a space to seperate those words? And, so people invent these cases as stylstic approaches to replace the use of 'spaces'.

Source

I am using Dapper (a C# micro-ORM). C# coding standards uses PascalCase. However, I'm reading from a database that uses snake_case. When reading from the database, how can I easily convert between the snake_case format to PascalCase?

For adhering to the naming conventions when mapping between snake_case database outputs and PascalCase C# objects, use:

Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true

If you also want to adhere to the naming conventions in SQL statements as well, you may want to look at this post.

public static class StringExtensions  
{
    public static string ToSnakeCase(this string input)
    {
        if (string.IsNullOrEmpty(input)) { return input; }

        var startUnderscores = Regex.Match(input, @"^_+");
        return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
    }
}

public static class UserSchema
{
    public static readonly Table { get; } = nameof(User).ToSnakeCase();

    public static class Columns
    {
        public static string Id { get; } = nameof(User.Id).ToSnakeCase();
        public static string Email { get; } = nameof(User.Email).ToSnakeCase();
        public static string FirstName { get; } = nameof(User.FirstName).ToSnakeCase();
        public static string LastName { get; } = nameof(User.LastName).ToSnakeCase();
    }
} 

var id = 123;
var sql = $@"
    SELECT {UserSchema.Columns.Id)},  
           {UserSchema.Columns.FirstName}, 
           {UserSchema.Columns.LastName}
    FROM   {UserSchema.Table}
    WHERE  {UserSchema.Columns.Id} = @{nameof(id)}";

var user = connection.Query<User>(sql, new { id }).SingleOrDefault();

How do I use git bisect to identify the root cause of a problem?

git bisect start

#If you do not provide a commit hash, we assume that you are referring to the current commit
git bisect bad 

git bisect good 2a21571edf01fda7d072b45618ca9e7047930d2c

#Then it will identify a possible commit
Bisecting: 38 revisions left to test after this (roughly 5 steps)
[8cfbb4ccba39d6496c9763bc907633aa365d24b5] Example Commit

#Mark whether this git bisect is good or bad to move onto the next commit...
git bisect bad

#Eventually, we will find the first 'bad' commit.
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[30c3db8532496ee34bb60ffc2d88dd693f2cdfd3] Another Example Commit

#Remember to reset back to HEAD when you finish looking for bad commits
git bisect reset

More Information:

I have two values that both share the same generic Type (T), but cannot be compared to each other, despite both of them being intended as "reference types". How can I fix that?

The compiler doesn't know they're reference types. So you need to add a type constraint to prove that they're indeed reference type. This is the type constraint you should add: where T : class

For more information, please read Can't operator == be applied to generic types in C#?.

In Racket, what's the difference between square brackets ([ ]) and parentheses (( ))?

None. However, there is a convention to use [ and ] for cond clauses. For more information, please read What is the difference between [ ] and ( ) brackets in Racket (lisp programming language)?.

Why do Racket lists sometimes have dots (for example: (2 3 . 5))?

According to this StackOverflow answer, by Sylwester:

The dot is not uniquely a racket thing, but a lisp thing. A list is made out of pairs and one pair has the literal form (car . cdr) and a list of the elements 2, 3 is made up like (2 . (3 . ())) and the reader can read this, however a list that has a pair as it's cdr can be shown without the dot and the parens such that (2 . (3 . ())) is the same as (2 3 . ()). Also a dot with the special empty list in the end can be omitted so that (2 3) is how it can be read and the only way display and the REPL would print it.

What happens if you don't have a pair or null as the cdr? Then the only way to represent it is as a dotted. With (2 . (3 . 5)) you can only simplify the first dot so it's (2 3 . 5).

You may also want to read Racket's documentation on pairs as well.

A website was referring to the latest Bootstrap CSS file (<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">) back when Bootstrap was on 3.x. The website looked perfect! Then Bootstrap upgraded to 4.x, breaking the whole site's design and behavior. What do I do?

Change the CDN reference to only refer to the last Bootstrap 3.x file ( <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">).

How do I set a default git commit message?

I want to have the URL hold the 'state' of the user application. What resources should I look at?

My approach is:

  1. Write a Container Compotent (otherwise known as a "smart compontent") that can reads from the URL and store that info into its current state.
  2. When writing the componentDidMount() method, make sure to add a listener to history. Whenever the URL changes, read from the URL and store that info into the Container Compontent's current state.
    constructor(props) {
        super(props);

        this.state = {
            query: history.location.hash,
        };
    }
    
    componentDidMount() {
      history.listen((location, action) => {
        this.setState({
          query : history.location.hash
        });
      })
    }

Then, we simply update the history.location.hash wherever we wish, thereby triggering the state update (and the associated re-render of the compontent).

What resources should I look at to figure out how to migrate from Sublime Text 2 to Sublime Text 3?

How do I set up a localhost SSL certificate for OSX?

openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt -subj '/CN=localhost'
sudo security add-trusted-cert -p ssl -d -r trustRoot -k ~/Library/Keychains/login.keychain localhost.crt

Source: https://stackoverflow.com/a/32169444

How do I configure create-react-app to use a custom localhost certificate, on OSX?

HTTPS=true SSL_CRT_FILE=path/to/cert.crt SSL_KEY_FILE=path/to/cert.key npm start

...or, you can include in the npm start script

{
  "start": "HTTPS=true SSL_CRT_FILE=path/to/cert.crt SSL_KEY_FILE=path/to/cert.key react-scripts start"
}

Source: https://create-react-app.dev/docs/using-https-in-development/

Can I configure create-react-app to use its own self-signed certificate (rather than me providing it with a self-signed certificate)?

Sure! Just pass HTTPS=true instead, and create-react-app will use its own self-signed certificate instead.

HTTPS=true npm start
{
  "start": "HTTPS=true react-scripts start"
}

Source: https://create-react-app.dev/docs/using-https-in-development/

If I am using webpack, how should I import a json file into a .js file?

From sokra's comment on a GitHub issue:

"import config from './config.json' will give you the raw json data. This is the official way to import json data.

import { key } from './config.json' will give you a key from the json data.

import * as config from './config.json' will give you the generate namespace object from the json module.

require('./config.json') will give you the raw json data."

My hosts file is being ignored by Firefox. What should I do to fix this issue?

What's an easy way to generate random sci-fi planet names similar to the planets in the Elite series? (Use JavaScript for this problem.)

let R = (n) => (Math.random() * n) | 0

function eliteStarSystemName(){
	let name = ""
	for(let l=R(2.5)+2;l--;)
		name += "LEXEGEZACEBISOUSESARMAINDIREA.ERATENBERALAVETIEDORQUANTEISRION".substr(R(31)*2,2)
	return name.replace(".", "")
} 

for(let w=50;w--;){
	document.write(eliteStarSystemName() + "<br/>")
}

Source

Note that, in the ProcJam discord, the author of this code claimed that n | 0 is equal to Math.floor(n).

repl.it is not working with my Ruby gems. It's stating the following errors when it tried installing gems:

Errno::EACCES: Permission denied @ rb_file_s_rename - (/home/runner/.gem/ruby/2.5.0/cache/bcrypt-3.1.16.gem, /var/lib/gems/2.5.0/cache/bcrypt-3.1.16.gem) (Bundler::InstallError)
"from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file "calyx"
  1. Create a .bundle folder by using repl.it's Universal Package Manager's GUI to "manually" install the gems you need. UPM has the permissions to install Ruby gems...you don't, so use UPM. (That way, the packages would already be installed on your machine, so you don't need to worry about the gems not being installed if you lack the proper permissions to do so - since repl.it .)
  2. Create a .replit file with the following text:
run="bundle exec ruby main.rb"

It is possible you really only need to create the .replit file and do not need create the .bundle folder as well, but I cannot be certain of that, and it's probably safer to do step 1. If you are using bundler/inline, you don't have to remove that code snippet - it will should simply reuse the gems you already installed via the Universial Package Manager.

How do I extract images from a PDF file?

Download xpdf (possibly using homebrew if you are using MacOSX) and then use pdfimages -j c:\path\to\your.pdf c:\path\to\where\you\want\images\prefix\. Trailing slash is necessary to ensure that it doesn't dump all images into the parent directory. The -j extracts all JPEGs in the format of prefix-00N.jpg, while extracting all other images as prefix-00N.ppm (where ppm stands for Portable PixMap).

Source

I need a recipe for using httrack...

This recipie mirrors the sites https://example.com/forum/cool_forum_a and https://example.com/forum/cool_forum_b and save them in the local folder /Users/generic_user/websites/example_cool_forums, blacklisting any URLs that contains ?. We also should save files located in the directory https://example.com/topic/* as well, if they are being linked to in cool_forum_a and cool_forum_b.

httrack https://example.com/forum/cool_forum_a https://example.com/forum/cool_forum_b -W -O "/Users/generic_user/websites/example_cool_forums" -%v https://example.com/topic/\* '-?'

I am writing a bash script that deals with a string with special characters (<, >, |, &, etc.). How do I ensure that bash properly handles such a string?

Make sure you quote the string in full! For example:

echo "This is a string with the special character &"

For more information, consult Special Characters and Quoting.

How do I sumbit links to Internet Archive from the command line?

Use this Python package https://github.com/agude/wayback-machine-archiver or the Ruby package https://github.com/buren/wayback_archiver .

How do I customize the Powershell colors on a Mac?

Type $profile in the Mac Powershell script find the location of your profile file (which is generally ~/.config/powershell/Microsoft.Powershell_profile.ps1). If no file or folder exist in that location, then create one. Powershell runs this script every time you open up a new shell, so any commands you place there will be executed.

Run Get-PSReadLineOption to find out the current color pallette.

Update the profile file to include your changes to the current color pallete. For example, if I want to change the color of the Command text to "dark red", I update the profile to include the following command:

Set-PSReadLineOption -Colors @{
 "Command" = [ConsoleColor]::DarkRed
}

Source: https://archive.ph/qhSk7

I want to prevent people from putting data into a form field. So I mark that form field as disabled. Yet the form will not submit data from said form field. What should I use instead?

Use readonly. The form field will still prevent user input, but the data will still be sent as approriate when the form is submitted.

From https://stackoverflow.com/questions/7730695/whats-the-difference-between-disabled-disabled-and-readonly-readonly-for-ht:

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit. Another difference is that readonly elements can be focused (and getting focused when "tabbing" through a form) while disabled elements can't.

Read more about this in this great article or the definition by w3c. To quote the important part:

Key Differences

The Disabled attribute

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.

The Read Only Attribute

  • Not all form elements have a readonly attribute. Most notable, the <SELECT> , <OPTION> , and <BUTTON> elements do not have readonly attributes (although they both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only. (This can be a problem… see below.)
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

When should I use readonly and when should I use disabled?

From https://ux.stackexchange.com/questions/118020/best-practice-readonly-vs-disabled-in-form-controls/136269#136269

Readonly controls cannot be changed by the user.

Disabled controls cannot be changed by the user, or interacted with -- tab, focus, included in form submission (exception: the text can still be selected). Additionally they have muted styling.

Best practice

Use readonly controls for values that cannot be changed by the user, but are still significant.

Use disabled for values are not applicable currently, but could be enabled in a different state.

For example, in your case, a readonly input makes sense. The control is just like the others, except that the user can't directly modify it.

In another example, suppose I was ordering a mug, and could add a custom message to it. I'd use a disabled input for the message, because it's irrelevant until I enable the checkbox.

Why can't I run the antlr tool properly?

From installation docs:

If you get a no class definition found error, you are missing the ANTLR jar in your CLASSPATH (or you might only have the runtime jar):

/tmp $ java org.antlr.v4.Tool Hello.g4
Exception in thread "main" java.lang.NoClassDefFoundError: org/antlr/v4/Tool
Caused by: java.lang.ClassNotFoundException: org.antlr.v4.Tool
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
   at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

It is possible you may have forgot to copy and paste the full CLASSPATH as recommended in the Getting Started document:

$ export CLASSPATH=".:/usr/local/lib/antlr-4.10.1-complete.jar:$CLASSPATH"

$ alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.10.1-complete.jar:$CLASSPATH" org.antlr.v4.Tool'
$ alias grun='java -Xmx500M -cp "/usr/local/lib/antlr-4.10.1-complete.jar:$CLASSPATH" org.antlr.v4.gui.TestRig'

As suggested by this StackOverflow answer, you also want to make sure that the name of the grammar also matches the filename in question.

> antlr4 hello.g4 
error(8): hello.g4:1:8: grammar name Hello and file name hello.g4 differ

In C#, I get this error at runtime - "An expression tree may not contain a call or invocation that uses optional arguments". How do I fix this?

Why: Because you are not providing the optional parameters when calling the method. Mainly you get this with .net core when using IAsyncProxy service object.

Fix: Pass all the optional parameters value, you may use default value if you. Source

The underlying expression tree API does not support optional arguments.

For IL-compiled code the C# compiler inserts the default values at compile time (hard-coded), because the CLR does not support calling methods with optional arguments either when the arguments are not provided explicitly.

Source

Interpreation: Normally, when you are writing code using C#, optional parameters will be handled for you by the compiler. However, there's situations (like, say, when you're writing LINQ to SQL) where this doesn't happen, thereby throwing the error. You'll need to fill the optional parameters yourself. If oyu don't care, just provide the default values.

TL;DR: Optional parameters aren't actually optional when you're dealing with certain situations, like LINQ to SQL.

When I copy and paste data from Azure Data Studio, the resulting text is all on one line, even if you know the data in question consists of multiple lines. What setting must I change so that when I copy/paste data, I see the resulting text take up multiple lines?

Go to: Settings > Data > Query Editor > Results: Copy Remove New Line---brendonlallen

Source

In SQL, how do I insert in special Unicode characters like '≥' ?

First, make sure that your column actually support special Unicode characters. Your column supports it if it has the following datatype:

  • nchar
  • nvarchar
  • ntext

Then, you prefix the string with N. For example N'≥'. The N symbol lets SQL knows that this string is nvarchar instead of a standard varchar, and thus a string that needs Unicode support.

Source A: Inserting special characters (greater/less than or equal symbol) into SQL Server database

By the way, if the string is interperted as varchar, then SQL would use whatever codepage it was configured for - which is already bad news because this means "different behavior on different machines". This generally isn't a problem becuase the default codepage seems to be ASCII, which means it works most of the time, but if you encounter something that requires Unicode, the result would fails horribly. For example, would be converted into =. Therefore, some auto-generated INSERT scripts prefix every string with N (so that the string gets interperted as nvarchar), just to avoid this potential edge case.

Source B: What does N' stands for in a SQL script ? (the one used before characters in insert script)

How do you recover local data from Postman? This may be useful in a scenario where you save collections without log onto Postman, only to later log onto Postman?

First, locate where Postman Collections are saved, using https://stackoverflow.com/questions/47399809/where-are-postman-collections-saved . For MacOS, Postman Collections are saved at:

Users/USER_NAME/Library/Application Support/Postman/backup-YYYY-MM-DDTHH:mm:ss.SSSZ.json

Then, import the resulting json file into the logged in Postman app.

A model in .NET isn't being parsed properly (for example, the resulting object is null). How do I check what errors is causing the model to not be parsed properly?

In the Immediate Window, type ModelState to access the model. ModelState.Values will let you access the values buried inside there, and then you can try to access the Errors within those values.

When I am using a Csv.CsvReader in C#, I get the following error: "Duplicate headers detected in HeaderPresent mode. If you don't have a header you can set the HeaderMode to HeaderAbsent." What can I do to fix this?

First, check to see if the same header column shows up multiple times in the header. If that happens, that's what triggering the issue.

Second, check to see if there are any blank header columns. If so, then these blank header columns could also confuse Csv.CsvReader as well. That being said, when I encountered this specific situation, there were multiple blank header columns, so it is possible that it was the duplication of those columns that raised the issue, not the fact that it was blank outright.

Github Issue

Link To Specific Code Causing Error

How do I log onto SQL Server Management Studio's localhost database?

From https://www.koskila.net/how-to-access-local-mssql-server-using-sql-server-management-studio/:

Essentially, just paste this into the connection window:

(localdb)\MSSqlLocalDb

If that doesn't work, the URL also provides an alternative method to extract a "the instance name pipe – a weird, nonsensical URI-looking piece of textual vomit you simply can’t guess". You will connect to this "instance name pipe" instead.

How do I schedule a meeting with multiple people in different zones?

Use a tool like a World Clock Meeting Planner to compare differnet time zones and find overlapping availabilities that can work for all parties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment