idioms

package
v0.0.0-...-be3c365 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2023 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AllLangs []string
View Source
var AllNiceLangs []string
View Source
var RegexpDigitsOnly = regexp.MustCompile("^\\d+$")

Functions

func AllLanguages

func AllLanguages() []string

func CloneStringSlice

func CloneStringSlice(a []string) []string

CloneStringSlice makes a defensive copy of

func Concurrent

func Concurrent(funcs ...func())

Concurrent launches provided funcs, and waits for their completion.

func ConcurrentPromise

func ConcurrentPromise(funcs ...func()) chan bool

Concurrent launches provided funcs, and returns a channel to notify completion.

func ConcurrentWithAllErrors

func ConcurrentWithAllErrors(funcs ...func() error) (ok bool, errs []error)

ConcurrentWithAllErrors launches provided funcs, and gathers errors. If no errors, ok is true and the returned slice contains all nil values.

func ConcurrentWithAnyError

func ConcurrentWithAnyError(funcs ...func() error) error

ConcurrentWithAnyErrors launches provided funcs, and returns 1 error if at least 1 error occurred, nil otherwise.

func FilterOut

func FilterOut(s []string, forbidden []string) []string

FilterOut creates a new slice from s, removing any element contained in forbidden. Accept nils and empty lists. Never yields nil, but may yield an empty list.

func FilterStrings

func FilterStrings(s []string, fn func(string) bool) []string

FilterStrings creates a new slice from s, removing any element that doesn't match the predicate fn.

From https://blog.golang.org/go-slices-usage-and-internals

Accept nils and empty lists. Never yields nil, but may yield an empty list.

Items that match the predicate are kept (not thrown away, do not confuse!)

func Flatten

func Flatten(s string) string

Flatten replaces newlines by spaces

func LanguageAutoComplete

func LanguageAutoComplete(fragment string) []string

func LanguageExtraKeywords

func LanguageExtraKeywords(lg string) []string

func Last

func Last(array []string) (result string)

Last returns the last element of a slice, or empty string if the slice is empty.

func MainStreamLanguages

func MainStreamLanguages() []string

Return alpha codes for each language (no encoding problems). See PrintNiceLang to display them more fancy.

func MapStrings

func MapStrings(str []string, f func(string) string) []string

MapStrings applies f to each element of str, and returns a new slice of the same size containing all the results.

func Max

func Max(a, b int) int

Max returns the maximum of a and b.

func Min

func Min(a, b int) int

Min returns the minimum of a and b.

func MoreLanguages

func MoreLanguages() []string

func NoCR

func NoCR(s string) string

CRLF -> LF

func NormLang

func NormLang(lang string) string

func NormalizeRunes

func NormalizeRunes(str string) string

NormalizeRunes discard special characters from a string, for indexing and for searching. Some letters with diacritics are replaced by the same letter without diacritics.

func PrintNiceLang

func PrintNiceLang(lang string) string

func PrintNiceLangs

func PrintNiceLangs(langs []string) []string

func RemoveEmptyStrings

func RemoveEmptyStrings(s []string) []string

RemoveEmptyStrings creates a new slice from s, removing all empty elements.

func Sha1hash

func Sha1hash(s string) string

Sha1hash is a shorthand to get a sha1 hash as a string.

func Shorten

func Shorten(s string, n int) string

Shorten keeps only the n first bytes, add appends "..." if needed.

func SplitForIndexing

func SplitForIndexing(s string, normalize bool) []string

SplitForIndexing cuts sentences or paragrahs into words. Words of 2 letters of less are discarded.

func SplitForSearching

func SplitForSearching(s string, normalize bool) []string

SplitForSearching cuts an input search string into a slice of search terms.

func String2Int

func String2Int(str string) int

String2Int is a shorthand to convert a string to an int. It doesn't panic and does'nt return any error, but it may return -1. Thus it should be used only to parse positive integer that are extermely likely to be well-formed.

func StringSliceContains

func StringSliceContains(hay []string, needle string) bool

StringSliceContains determines whether this slice contains this string

func StringSliceContainsCaseInsensitive

func StringSliceContainsCaseInsensitive(hay []string, needle string) bool

StringSliceContainsCaseInsensitive determines whether this slice contains this string, regardless the case

func StringSliceEquals

func StringSliceEquals(a []string, b []string) bool

StringSliceEquals determines whether two string slices are the same. Arbitrary regards nil and []string{} as NOT equal.

func Truncate

func Truncate(s string, maxChars int) string

func TruncateBytes

func TruncateBytes(s string, maxBytes int) string

Types

type Idiom

type Idiom struct {
	// Id is auto-incremented 1, 2, 3...
	// TODO name ID instead
	Id int

	// Reserved in case one idiom derived from another
	// TODO name OrigID instead
	OrigId int

	// Title is like the "idiom name"
	Title string

	// LeadParagraph is the idiom Description : 1 to 3 lines are fine
	LeadParagraph string

	// ExtraKeywords for indexation+search
	ExtraKeywords string

	// Author is the name of the original creator of this idiom on this website
	Author string

	// CreationDate is the date of creation of this idiom on this site
	CreationDate time.Time

	// LastEditor is the name of the last person who modified this idiom
	LastEditor string

	// EditSummary is the comment explaining why LastEditor made the edit.
	// It is not displayed except in history views.
	EditSummary string

	// LastEditedImplID is the ID of the only impl modified by
	// last edit. LastEditedImplID should be 0 if last
	// edit was on the idiom statement, not on an impl.
	LastEditedImplID int

	// Please acknowledge sources (idiom statement, not snippet).
	OriginalAttributionURL string

	// Picture representing the concept, if necessary
	// DEPRECATED
	Picture string

	// ImageURL to illustrate this idiom.
	ImageURL string

	// ImageWidth, ImageHeight hints for web rendering: avoids FOUC
	ImageWidth, ImageHeight int

	// ImageAlt is a description of a picture for accessibility purpose
	ImageAlt string

	// Autoincremented at each update 1, 2, 3...
	Version int

	// Date of last update
	VersionDate time.Time

	// List of implementations of this idiom in specific languages
	Implementations []Impl

	// (Denormalized) number of contained implementation, for datastore querying
	ImplCount int

	// How many votes for the idiom itself  (votes up - votes down)
	Rating int

	// Index-like array of important words : those from the title
	// DEPRECATED: use the new Text Search API instead.
	WordsTitle []string

	// Index-like array of words from title, description and implementation contents
	// DEPRECATED: use the new Text Search API instead.
	Words []string

	// Did the admin validate this idiom statement ?
	Checked bool

	// Extra calculated data like "Has this idiom been upvoted by this user?"
	// Ignored by the datastore.
	Deco IdiomRenderingDecoration `datastore:"-" json:"-"`

	// Related idioms ids "See also..."
	RelatedIdiomIds []int

	// NoSQL-style : store directly some data from other objects
	RelatedIdiomTitles []string

	// Protected when "only admin can edit"
	Protected bool

	// Variables from the lead paragraph, that we'd like every
	// impl snippet to contain
	Variables []string

	// RelatedURLs as extra pieces of documentation for the idiom statement.
	RelatedURLs []string

	// RelatedURLLabels are nice text for Related URLs hyperlinks.
	RelatedURLLabels []string
}

Idiom is the main entity of programming-idioms.org . An Idiom contains its Implementations. It is in theory independent from any framework, but has been used only in Google App Engine so far.

func (*Idiom) AddRelation

func (idiom *Idiom) AddRelation(other *Idiom)

AddRelation creates a bidirectional link between 2 related Idioms.

func (*Idiom) ExtractIndexableWords

func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string)

ExtractIndexableWords compute the list of words contained in an Idiom. First return value is the list of all matchable words. Second return value is the list of matchable words from title only.

func (*Idiom) FindIdiomOrImplLastEditor

func (idiom *Idiom) FindIdiomOrImplLastEditor() string

FindIdiomOrImplLastEditor returns last user who touched something

func (*Idiom) FindImplInIdiom

func (idiom *Idiom) FindImplInIdiom(implId int) (int, *Impl, bool)

FindImplInIdiom is a (unoptimized) iteration to retrieve an Impl by its ID, inside an Idiom.

It returns a pointer to the Impl, not a copy.

func (*Idiom) FindRecentlyUpdatedImpl

func (idiom *Idiom) FindRecentlyUpdatedImpl() *Impl

FindRecentlyUpdatedImpl is a (unoptimized) iteration to retrieve the most recently updated impl, inside an Idiom.

It returns a pointer to the Impl, not a copy.

func (*Idiom) VariablesComma

func (idiom *Idiom) VariablesComma() string

VariablesComma e.g. ["x", "result"] -> "x,result"

type IdiomHistory

type IdiomHistory struct {
	// Just embeds Idiom
	Idiom
	// If needed, add specific history fields
	UpdatedImplId int
	// TODO: how to get rid properly?
	// Got `datastore: cannot load field "EditorSummary" into a "pig.IdiomHistory": no such struct field`
	EditorSummary string `deprecated`
	// IdiomOrImplLastEditor is redundant storage of most recent impl update's editor,
	// to be directly indexed and displayed in history list.
	IdiomOrImplLastEditor string
}

IdiomHistory stores all the history: old versions of Idioms.

func (*IdiomHistory) AsIdiomPtr

func (ih *IdiomHistory) AsIdiomPtr() *Idiom

func (*IdiomHistory) ComputeIdiomOrImplLastEditor

func (hist *IdiomHistory) ComputeIdiomOrImplLastEditor()

ComputeIdiomOrImplLastEditor computes IdiomOrImplLastEditor

type IdiomRenderingDecoration

type IdiomRenderingDecoration struct {
	UpVoted   bool
	DownVoted bool
}

IdiomRenderingDecoration is the "current user" vote on this Idiom, if any. This struct does not contain the Idiom ID, so it must be part of a larger struct.

type IdiomVoteLog

type IdiomVoteLog struct {
	IdiomId int
	// Typicaly +1 or -1
	Value int
	// IpHash stored only to prevent abusive multiple votes
	IpHash string
	Date   time.Time
}

IdiomVoteLog is a history trace of an Idiom vote, from a specific user. This struct does not contain the nickname of the voter. However it does contain the Idiom ID. Each vote will have a voting booth as ancestor, specific for the nickname.

type Impl

type Impl struct {
	// Id is Internal. Not displayed on screen (but present in URL).
	// TODO name ID instead
	Id int

	// OrigId is reserved in case one impl derived from another
	// TODO name OrigID instead
	OrigId int

	// Author is the name of the original creator of this implementation on this site.
	Author string

	// CreationDate of this implementation on this website
	CreationDate time.Time

	// LastEditor is the name of the last person who modified this impl.
	LastEditor string

	// LanguageName is the programming language of this impl.
	// It is used to visualy identify the impl inside the idiom.
	// But note that an idiom may have several implementations for same language.
	LanguageName string

	// CodeBlock contains the snippet.
	// It should contain only instructions code, not comments.
	CodeBlock string

	// OriginalAttributionURL: please acknowledge sources.
	OriginalAttributionURL string

	// DemoURL is an optional link to an online demo
	DemoURL string

	// DocumentationURL is an optional link to official doc
	DocumentationURL string

	// AuthorComment comments about the CodeBlock.
	// This comment is always displayed on the right of the code.
	// TODO rename this to CodeBlockComment.
	AuthorComment string

	// Version is incremented at each update 1, 2, 3...
	Version int

	// VersionDate of last update
	VersionDate time.Time

	// Rating is the votes count for this specific impl  (votes up - votes down)
	Rating int

	// Checked is true if an admin has validated this implementation.
	Checked bool

	// ImplRenderingDecoration is some extra calculated data like "Has this implementation been upvoted by this user?"
	// Ignored by the datastore.
	Deco ImplRenderingDecoration `datastore:"-" json:"-"`

	// ImportsBlock contains the import directives, appart from main code section.
	ImportsBlock string

	// PictureURL to illustrate this impl.
	PictureURL string

	// Protected when "only admin can edit"
	Protected bool
}

Impl is a specific implementation of one Idiom in one programming language. It is in theory independent from any framework, but has been used only in Google App Engine so far.

func (*Impl) ExtractIndexableWords

func (impl *Impl) ExtractIndexableWords() []string

ExtractIndexableWords compute the list of words contained in an Impl.

type ImplRenderingDecoration

type ImplRenderingDecoration struct {
	UpVoted   bool
	DownVoted bool
	// Matching is set to true if current impl matches user text search query.
	Matching bool
	// SearchedLang is set to true if current impl lang is the user typed lang.
	SearchedLang bool
}

ImplRenderingDecoration is the "current user" vote on this Impl, if any. This struct does not contain Impl ID nor Idiom ID, so it must be part of a larger struct.

type ImplVoteLog

type ImplVoteLog struct {
	IdiomId int
	ImplId  int
	// Typicaly +1 or -1
	Value int
	// IpHash stored only to prevent abusive multiple votes
	IpHash string
	Date   time.Time
}

ImplVoteLog is a history trace of an Impl vote, from a specific user. This structure does not contain the nickname of the voter. However it does contain the Idiom ID and Impl ID. Each vote will have a voting booth as ancestor, specific for the nickname.

type LanguageSingleSelector

type LanguageSingleSelector struct {
	// Name of the HTML element
	FieldName string
	// Value of the widget: standardized name of a programming language
	Selected string
}

LanguageSingleSelector is used to specify the prefilled value of a programming language selection widget.

type MessageForUser

type MessageForUser struct {
	CreationDate,
	FirstViewDate,
	LastViewDate,
	DismissalDate,
	ExpirationDate time.Time
	Message  string
	Username string
}

type PageMeta

type PageMeta struct {
	// PageTitle is the title of this page
	PageTitle string
	// CanonicalURL helps deduplicating pages for SEO.
	// See https://support.google.com/webmasters/answer/139066
	CanonicalURL string
	// PageKeywords for meta tag "keyword"
	PageKeywords string
	// Toggles (global or custom) used to tune the output
	Toggles Toggles
	// SearchQuery is printed in search field, in case of new similar search
	SearchQuery string
	// ExtraCss after programming-idioms.css
	ExtraCss []string
	// ExtraJs after programming-idioms.js
	ExtraJs []string
	// PreventIndexingRobots for edit pages, etc.
	PreventIndexingRobots bool
}

PageMeta is basic metadata useful for any web page.

type Toggles

type Toggles map[string]bool

Toggles should always be named after the positive feature they represent, and default value should be true.

func (Toggles) All

func (t Toggles) All(names ...string) bool

func (Toggles) Any

func (t Toggles) Any(names ...string) bool

type UserProfile

type UserProfile struct {
	Nickname          string
	FavoriteLanguages []string
	SeeNonFavorite    bool
	// IsAdmin will never be set by user himself
	IsAdmin bool
}

UserProfile is a soft (non-secure) user profile

func EmptyUserProfile

func EmptyUserProfile() UserProfile

func (UserProfile) Empty

func (u UserProfile) Empty() bool

Empty means the visitor doesn't have any meaningful profile data in her cookies.

func (UserProfile) String

func (u UserProfile) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL