working on it ...

Filters

Explore Public Snippets

Sort by

Found 538 snippets matching: suggestions

    public by cghersi modified Jul 2, 2014  7471  1  7  2

    Java SWT: Combobox with AutoSuggestion feature

    This component can be safely used when you want to have a combobox with the capability to display automatic filtered suggestions based on the text already entered. It uses a couple of callback actions so that the caller can specify what to do when ENTER key is hit and how to load suggestions. The call back actions are specified by a simple interf
    package com.snip2code.ui.swt;
    
    import java.util.List;
    import java.util.Random;
    
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.StackLayout;
    import org.eclipse.swt.events.FocusAdapter;
    import org.eclipse.swt.events.FocusEvent;
    import org.eclipse.swt.events.KeyAdapter;
    import org.eclipse.swt.events.KeyEvent;
    import org.eclipse.swt.events.MouseAdapter;
    import org.eclipse.swt.events.MouseEvent;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Control;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Table;
    import org.eclipse.swt.widgets.TableItem;
    import org.eclipse.swt.widgets.Text;
    
    import com.snip2code.utils.Utils;
    
    
    /**
     * (c) 2011 snip2code inc.
     * This software is property of snip2code inc. Use or reproduction without permission is prohibited 
     *
     * This widget creates a textfield with an autosuggestion feature.
     * The list of suggestion is shown when the user clicks on the text field or starts typing in the text field
     */
    public class AutoSuggestionComposite extends Composite {
    
    	protected static Logger log = Logger.getLogger(AutoSuggestionComposite.class);
    	
    	private Composite textBoxStackPanel;
    	private StackLayout textboxLayout;
    	private Text textBox;
    	private Label tooltip;
    	private Shell popupShell;
    	private Table table;
    	private String tooltipMsg;
    
    	private ICallback<String, List<String>> loadSuggestionAction;
    	private ICallback<String, String> onEnterAction;
    	
    	private String text;
    	private int numOfDisplayedSuggestions;
    	
    	private static final String POPUPVISIB = "$$$POPUP_VISIB";
    	
    	private String uniqueID; //used to differentiate AutoSuggestion composites in the same dialog
    	private static Random rdn = new Random();
    	
    	/**
    	 * Create the dialog.
    	 * @param parent
    	 * @param style
    	 * @param tooltipMsg message to display when no input is entered
    	 * @param numOfDisplayedSuggestions masimum number of items suggested in the popup of suggestions
    	 * @param loadSuggestionAction callback to routine that loads the suggestions for autocomplete
    	 * @param onEnterAction callback when enter is pressed on the textbox
    	 */
    	public AutoSuggestionComposite(Composite parent, int style, String tooltipMsg, int numOfDisplayedSuggestions, 
    			ICallback<String, List<String>> loadSuggestionAction, ICallback<String, String> onEnterAction) {
    		super(parent, style);
    
    		textboxLayout = new StackLayout();
    		this.loadSuggestionAction = loadSuggestionAction;
    		this.onEnterAction = onEnterAction;
    		this.numOfDisplayedSuggestions = numOfDisplayedSuggestions;
    		this.tooltipMsg = tooltipMsg;
    		
    		uniqueID = rdn.nextInt() + tooltipMsg;
    		
    		createDialogArea();
    	}
    	
    	private void createDialogArea() {
    		this.setBackground(SWTUIUtilities.WHITE);
    		GridLayout gridLayout = new GridLayout();
    		gridLayout.marginHeight = 0;
    		gridLayout.marginWidth = 0;
    		this.setLayout(gridLayout);
    
    		//Panel with textbox and tooltip:
    		textBoxStackPanel = new Composite(this, SWT.NONE);
    		textBoxStackPanel.setLayout(textboxLayout);
    		GridData gdPanel = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    		gdPanel.verticalIndent = 2;
    		textBoxStackPanel.setLayoutData(gdPanel);
    		
    		tooltip = new Label(textBoxStackPanel, SWT.NONE);
    		tooltip.setBackground(SWTUIUtilities.WHITE);
    		tooltip.setForeground(SWTUIUtilities.LIGHT_GREY);
    		tooltip.setFont(SWTUIUtilities.LBL_TEXT);
    		tooltip.setText(" " + tooltipMsg); //manual horizontal indent, cause StackLayout doesn't allow this feature
    		tooltip.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseDown(MouseEvent e) {
    				setControlVisib(textBox, true);
    				textBoxStackPanel.layout();
    				textBox.setFocus();
    				loadSuggestions(null);
    			}
    		});
    		
    		textBox = new Text(textBoxStackPanel, SWT.NONE);
    		textBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
    		textBox.setFont(SWTUIUtilities.LBL_TEXT);
    		textBox.setBackground(SWTUIUtilities.WHITE);
    		textBox.setData(POPUPVISIB, uniqueID);
    		
    		//popup for suggestions:
    		popupShell = new Shell(getShell().getDisplay(), SWT.ON_TOP);
    		popupShell.setLayout(new FillLayout());
    		popupShell.setData(POPUPVISIB, uniqueID);
    		popupShell.setBackground(SWTUIUtilities.WHITE);
    		table = new Table(popupShell, SWT.SINGLE);
        	table.getVerticalBar().setVisible(false);
    		table.setFont(SWTUIUtilities.LBL_TEXT);
    		table.setData(POPUPVISIB, uniqueID);
    		for (int i = 0; i < numOfDisplayedSuggestions; i++) {
    			new TableItem(table, SWT.NONE);
    		}
    		
    		//Key Listener for Keyboards events:
    		textBox.addKeyListener(new KeyAdapter() {
    			@Override
    			public void keyReleased(KeyEvent e) {
    				boolean loadSuggestions = true;
    				saveInput();
    				switch (e.keyCode) {
    					case SWT.ARROW_DOWN:
    						int index = (table.getSelectionIndex() + 1) % table.getItemCount();
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.ARROW_UP:
    						index = table.getSelectionIndex() - 1;
    						if (index < 0) 
    							index = table.getItemCount() - 1;
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.CR:
    					case SWT.LF:
    					case 16777296: //enter in numeric keypad
    						if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
    							textBox.setText(table.getSelection()[0].getText());
    						}
    						
    						loadSuggestions = false;
    						execEnterAction();
    
    						break;
    					case SWT.ESC:
    						popupShell.setVisible(false);
    						break;
    				}
    
    				//only for printable characters, load search history:
    				if (loadSuggestions && (e.keyCode < 256))
    					loadSuggestions(textBox.getText());
    				
    				log.debug("End of key listener");
    			}
    		});
    		
    		//make sure the input entered in the text box is saved and ready to use:
    		textBox.addFocusListener(new FocusAdapter() {
    			@Override
    			public void focusLost(FocusEvent e) {
    				log.debug("Focus lost by textbox of autosugg from " + tooltipMsg);
    				saveInput();
    				checkTooltipVisib();
    				handleFocusLost();
    			}
    			
    			@Override
    			public void focusGained(FocusEvent e) {
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				log.debug("Focus gained by textbox of autosugg from " + tooltipMsg);
    				loadSuggestions(textBox.getText());
    			}
    		});
    		textBox.addSelectionListener(new SelectionAdapter() {
    			@Override
    			public void widgetSelected(SelectionEvent e) {
    				checkTooltipVisib();
    			}
    		});
    		
    		table.addListener(SWT.DefaultSelection, new Listener() {
    			public void handleEvent(Event event) {
    				textBox.setText(table.getSelection()[0].getText());
    				execEnterAction();
    			}
    		});
    		
    		//hide the popup of suggestions if the focus is out:
    		Listener focusOutListener = new Listener() {
    			public void handleEvent(Event event) {
    				handleFocusLost();
    			}
    		};
    		table.addListener(SWT.FocusOut, focusOutListener);
    		textBox.addListener(SWT.FocusOut, focusOutListener);
    		textBoxStackPanel.addListener(SWT.FocusOut, focusOutListener);
    		popupShell.addListener(SWT.FocusOut, focusOutListener);
    		this.addListener(SWT.FocusOut, focusOutListener);
    
    		getShell().addListener(SWT.Move, new Listener() {
    			public void handleEvent(Event event) {
    				popupShell.setVisible(false);
    				checkTooltipVisib();
    			}
    		});
    		
    		checkTooltipVisib();
    	}
    	
    	private void handleFocusLost() {
    		/* async is needed to wait until focus reaches its new Control */
    		if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    			return;
    		getShell().getDisplay().asyncExec(new Runnable() {
    			public void run() {
    				log.debug("Running handleFocusLost for " + tooltipMsg);
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				Control control = getShell().getDisplay().getFocusControl();
    				log.debug("handleFocusLost for " + tooltipMsg + ": control is " + control + ";uniqueID:" + uniqueID);
    				if ((control == null) || (control.getData(POPUPVISIB) == null) || 
    					!control.getData(POPUPVISIB).toString().equals(uniqueID)) {
    					popupShell.setVisible(false);
    				}					
    			}
    		});
    	}
    	
    	/**
    	 * Determines the visibility of textbox content vs tooltip when the textbox is empty
    	 */
    	public void checkTooltipVisib() {
    		if (Utils.isNullOrEmpty(textBox.getText())) 
    			setControlVisib(tooltip, true);
    		else
    			setControlVisib(textBox, true);
    		textBoxStackPanel.layout();
    	}
    	
    	private void execEnterAction() {
    		saveInput();
    		popupShell.setVisible(false);
    		onEnterAction.exec(text);
    	}
    	
        private void loadSuggestions(String prefix) {
        	log.debug("loading suggestions for " + prefix);
    
    //		if (Utils.isNullOrEmpty(prefix))
    //			return;
        	
        	Rectangle textBounds = getShell().getDisplay().map(textBoxStackPanel, null, textBox.getBounds());
        	
    		//load suggestions:
        	List<String> suggestions = loadSuggestionAction.exec(prefix);
        	log.debug("loaded " + suggestions.size() + " suggestions");
        	
        	table.setItemCount(suggestions.size());
    		TableItem[] items = table.getItems();
    		int maxWidthOfItem = 0;
    		log.debug("Changing " + items.length + " items in TablePopup");
    		for (int i = 0; i < items.length; i++) {
    			if (i < suggestions.size()) {
    				String sugg = suggestions.get(i);
    				if (!Utils.isNullOrEmpty(sugg)) {
    					items[i].setText(sugg);
    					int w = items[i].getBounds().width;
    					if (w > maxWidthOfItem)
    						maxWidthOfItem = w;
    				}
    			}
    		}
    //		//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    //		if ((maxWidthOfItem + 10) < textBounds.width)
    //			table.pack();
    		
    		//23 pixels is the height of 1 item in the drop down list; 
    		//always add a blank line at the end of the list to improve readability
    		int popupHeight = (suggestions.size() + 1) * 23; 
    		log.debug("popupHeight for [" + this.tooltipMsg + "]:" + popupHeight);
    		if (popupHeight <= 46)
    			popupHeight = 46; 
    	
    		//set a cap to the maximum height of the popup (17 lines):
    		if (popupHeight > 391) {
    			popupHeight = 391;
    			table.getVerticalBar().setVisible(true);
    		} else {
    			//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    			if ((maxWidthOfItem + 10) < textBounds.width)
    				table.pack();
    			table.getVerticalBar().setVisible(false);
    		}
    		
    		log.debug("setBounds popup:" + textBounds.x + ";" + (textBounds.y + textBounds.height + 4) + ";" + 
    					textBounds.width + ";" + popupHeight);
    		popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height + 4, textBounds.width, popupHeight);
    		popupShell.setVisible(true);		
        }
        
    	private void setControlVisib(Control c, boolean visible) {
    		if (c == null)
    			return;
    		
    		if (visible) 
    			textboxLayout.topControl = c;
    	}
    	
    	private void saveInput() {
    		text = textBox.getText();
    		if (text == null)
    			text = "";
    		text = text.trim();
    	}
    	
    	/**
    	 * Returns the content of the textbox
    	 */
    	public String getText() {
    		return text;
    	}
    	
    	/**
    	 * Sets the content of the textbox
    	 */
    	public void setText(String text) {
    		this.text = text;
    		textBox.setText(text);
    		setControlVisib(textBox, true);
    	}
    	
    	/**
    	 * Hides the popup of suggestions
    	 */
    	public void hideSuggestions() {
    		popupShell.setVisible(false);
    	}
    	
    	@Override
    	public void dispose() {
    		if (popupShell != null) {
    			hideSuggestions();
    			popupShell.dispose();
    		}
    
    		super.dispose();
    	}
    }

    public by davis modified Jun 1, 2016  1111  1  3  0

    Atom autocomplete suggestions on tab

    Atom autocomplete suggestions on tab: tab-completion.coffee
    {Point} = require 'atom'
    
    atom.commands.add 'atom-text-editor', 'custom:tabcomplete', (e) ->
      editor = atom.workspace.getActiveTextEditor()
      cursor = editor.getLastCursor()
    
      {row, column} = cursor.getBufferPosition()
      precedingCharacter = editor.getTextInBufferRange([[row, column - 1], [row, column]])
    
      if /\S/.test(precedingCharacter)
        autocomplete = atom.packages.getActivePackage('autocomplete-plus')
        return unless autocomplete?
    
        manager = autocomplete.mainModule.activate()
        manager.shouldDisplaySuggestions = true
        manager.findSuggestions(true)
      else
        e.abortKeyBinding()
    
    
    

    public by Piers Mainwaring modified May 8, 2015  940  0  3  0

    Atom autocomplete suggestions on tab

    Atom autocomplete suggestions on tab: tab-completion.coffee
    {Point} = require 'atom'
    
    atom.commands.add 'atom-text-editor', 'custom:tabcomplete', (e) ->
      editor = atom.workspace.getActiveTextEditor()
      cursor = editor.getLastCursor()
    
      {row, column} = cursor.getBufferPosition()
      precedingCharacter = editor.getTextInBufferRange([[row, column - 1], [row, column]])
    
      if /\S/.test(precedingCharacter)
        autocomplete = atom.packages.getActivePackage('autocomplete-plus')
        return unless autocomplete?
    
        manager = autocomplete.mainModule.activate()
        manager.shouldDisplaySuggestions = true
        manager.findSuggestions(true)
      else
        e.abortKeyBinding()
    
    
    

    public by msdn modified Jan 12, 2015  1179  0  6  0

    CancelChanges: Method called to "invoke" the Screen's Interface method (CancelChanges) to explicitly cancel the changes

    Method called to "invoke" the Screen's Interface method (CancelChanges) to explicitly cancel the changes The IScreenObject representing the screen Screen here cannot be converter to a concrete IScreenWithListAndCurrentObject. For this reason Reflection is used. This is a "weakness" of the implementation. Any suggestions would be greatly ap
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Base.SL.Contracts;
    using Microsoft.LightSwitch.Framework.Base;
    using Microsoft.LightSwitch.Details.Framework.Base;
    using Microsoft.LightSwitch.Presentation.Extensions;
    using Microsoft.LightSwitch.Client;
    using Microsoft.LightSwitch.Presentation;
    using Microsoft.LightSwitch.Presentation.Implementation;
    using System.Reflection;
    using Microsoft.LightSwitch.Runtime.Shell.Framework;
    
    /// <summary>
    /// Method called to "invoke" the Screen's Interface method (CancelChanges) to explicitly cancel the changes
    /// </summary>
    /// <param name="screen">The IScreenObject representing the screen</param>
    /// <remarks>Screen here cannot be converter to a concrete  IScreenWithListAndCurrentObject<TEntity, TDetails>.
    /// For this reason Reflection is used.
    /// This is a "weakness" of the implementation. Any suggestions would be greatly appreciated.</remarks>
    private static void CancelChanges(IScreenObject screen)
    {
        MethodInfo mi = screen.GetType().GetMethod("CancelChanges");
        if (mi == null)
            return;
        mi.Invoke(screen, null);
    }

    external by Max Vorobev modified Jul 10, 2016  83  0  1  0

    AutoCompleteTextView that delays sending requests to adapter (needed if suggestions are being queried from external API). Also shows progress bar when loading suggestions.

    AutoCompleteTextView that delays sending requests to adapter (needed if suggestions are being queried from external API). Also shows progress bar when loading suggestions.: DelayAutoCompleteTextView.java
    import android.content.Context;
    import android.os.Handler;
    import android.os.Message;
    import android.util.AttributeSet;
    import android.view.View;
    import android.widget.AutoCompleteTextView;
    import android.widget.ProgressBar;
    
    
    public class DelayAutoCompleteTextView extends AutoCompleteTextView {
    
        private static final int MESSAGE_TEXT_CHANGED = 100;
        private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
    
        private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
        private ProgressBar mLoadingIndicator;
    
        private final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                DelayAutoCompleteTextView.super.performFiltering((CharSequence) msg.obj, msg.arg1);
            }
        };
    
        public DelayAutoCompleteTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public void setLoadingIndicator(ProgressBar progressBar) {
            mLoadingIndicator = progressBar;
        }
    
        public void setAutoCompleteDelay(int autoCompleteDelay) {
            mAutoCompleteDelay = autoCompleteDelay;
        }
    
        @Override
        protected void performFiltering(CharSequence text, int keyCode) {
            if (mLoadingIndicator != null) {
                mLoadingIndicator.setVisibility(View.VISIBLE);
            }
            mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
        }
    
        @Override
        public void onFilterComplete(int count) {
            if (mLoadingIndicator != null) {
                mLoadingIndicator.setVisibility(View.GONE);
            }
            super.onFilterComplete(count);
        }
    }
    
    // code sample
    location.setLoadingIndicator((ProgressBar)findViewById(R.id.progress_bar_id));
    
    

    external by NotYou64 modified Dec 16, 2016  15  0  1  0

    An amazing name generator that is not a GUI because I am a noob programmer! Any suggestions? Don't email me! Just comment in the section down below that is for suggestions and stuff!

    An amazing name generator that is not a GUI because I am a noob programmer! Any suggestions? Don't email me! Just comment in the section down below that is for suggestions and stuff!: amazingNameGenerator.py
    #!/usr/bin/python2.7
    
    """Cole D... HA! YOU TRIED TO SEE WHAT MY NAME IS! I'M NOT FALLING FOR THAT!
    age 12
    amazing programmer
    such a boss
    11-17-16"""
    
    #imports
    import random
    import time
    
    #arrays
    objects = ["Diary", "Bottle", "Water", "Packet", "Chewing Gum", "Tissue", "Glasses", "Watch", "Photo", "Camera", "Stamp", "Postcard", "Dictionary", "Coin", "Brush", "Credit Card", "Key", "Phone", "Wallet", "Button", "Umbrella", "Pen", "Pencil", "Lighter", "Cigarette", "Match", "Lipstick", "Purse", "Case", "Paper Clip", "Scissors", "Rubber", "File", "Passport", "Driving Licence", "Comb", "Notebook", "Laptop", "Rubbish", "Mirror", "Painkiller", "Sunscreen", "Toothbrush", "Battery", "Light Bulb", "Alarm Clock"]
    actionVerbs = ["Built", "Bargaining", "Adjusting", "Anticipating", "Aiding", "Boosted", "Confirmed", "Connected", "Capturing", "Caring", "Deducting", "Conserving", "Detailed", "Comfortable", "Debugging", "Defending", "Dispatched", "Educated", "Established", "Enlarged", "Focused", "Enforced", "Fixed", "Generated", "Furnished", "Funded", "Innovative", "Invented", "Identified", "Increased", "Labled", "Logged", "Influenced", "Insecure", "Maintained", "Mastered", "Merged", "Motivated", "Measured", "Observed", "Overseen", "Raised"]
    allDefiningStuff = ["Stupid", "Human", "Small", "Able", "Big", "High", "Little", "Last", "Bad", "Adorable", "Beautiful", "Clean", "Elegant", "Fancy", "Glamorous", "Handsome", "Long", "Magnificent", "Old-fashioned", "Plain", "Pathetic", "Sparkling", "Ugliest", "Unsightly", "Wide-eyed", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Gray", "Black", "White",  "Better", "Dead", "Famous", "Gifted", "Helpful", "Important", "Mushy", "Odd", "Powerful", "Rich", "Shy", "Tender", "Uninterested", "Vast", "Wrong", "Old", "Built", "Bargaining", "Adjusting", "Anticipating", "Aiding", "Boosted", "Confirmed", "Connected", "Capturing", "Caring", "Deducting", "Conserving", "Detailed", "Comfortable", "Debugging", "Defending", "Dispatched", "Educated", "Established", "Enlarged", "Focused", "Enforced", "Fixed", "Generated", "Furnished", "Funded", "Innovative", "Invented", "Identified", "Increased", "Labled", "Logged", "Influenced", "Insecure", "Maintained", "Mastered", "Merged", "Motivated", "Measured", "Observed", "Overseen", "Raised"]
    animals = ["Penguin", "Hound", "Elephant", "Frog", "Baboon", "Dog", "Toad", "Bear", "Owl", "Shark", "Bat", "Tiger", "Beetle", "Beagle", "Chicken", "Alligator", "Tortoise", "Bulldog", "Lizard", "Salamander", "Cat", "Unicorn", "Centipede", "Chimpanzee", "Cheetah", "Deer", "Dodo Bird", "Duck", "Otter", "Mole", "Mongoose", "Monkey"]
    
    #nickname types
    class nicknameTypes(object):
        def adjective(self, a, b, c):
            print"what is your name?"
            adNum = random.randrange(0,92)
            myName = raw_input()
    
            if myName == 'cole' or myName == "Cole":
                print"Your nickname is Cole the Super Amazing, smart, Cool guy that is better than everybody else"
                time.sleep(1)
                playAgain(a, b, c)
    
            #a = allDefiningStuff
            nickname = (myName.title()  + " the " + a[adNum])
            print("Your nickname is " + nickname)
    
        def adjectiveAnimal(self, a, b, c):
            adNum = random.randrange(0,92)
            anNum = random.randrange(0,32)
            print"what is your name?"
            myName = raw_input()
    
            if myName == 'cole' or myName == "Cole":
                print"Your nickname is Cole the Amazing Unicorn"
                time.sleep(1)
                playAgain(a, b, c)
    
            #a = allDefiningStuff     b = animals
            nickname = (myName.title() + " the " + a[adNum] + " " + b[anNum])
            print("Your nickname is " + nickname)
    
        def adjectiveObject(self, a, b, c):
            print"what is your name?"
            myName = raw_input()
    
            if myName == 'cole' or myName == "Cole":
                print"Your nickname is Cole the Amazing Enigma Machine"
                time.sleep(1)
                playAgain(a, b, c)
    
            adNum = random.randrange(0,92)
            adObj = random.randrange(0,42)
            #a = allDefiningStuff     b = objects
            nickname = (myName.title() + " the " + a[adNum] + " " + b[adObj])
            print("Your nickname is " + nickname)
    
        def nameAnimal(self, a, b, c):
            print"what is your name?"
            myName = raw_input()
    
            if myName == 'Cole' or myName == "cole":
                print"Your nickname is Cole the Unicorn"
                time.sleep(1)
                playAgain(a, b, c)
    
            anNum = random.randrange(0,32)
            #a = animals
            nickname = (myName.title() + " the " + a[anNum])
            print("your nickname is " + nickname)
    
    #        def nameObjects(self, a)
    
    #play again function
    def playAgain(a, b, c):
        print"Would you like another nickname?"
        playagain = raw_input()
    
        if playagain == 'yes' or playagain == 'Yes':
            print"Thought so"
            time.sleep(1)
            main(a, b, c)
    
        if playagain == "no" or playagain == 'No':
            print"well skrew you too"
            for i in range(1,1000000):
                print 1000000 - i
                time.sleep(1)
    
    #function
    def main(a, b, c):
        global n
        n = nicknameTypes()
        print"                                         "
        print"What kind of nickname would you like?(1-4)"
        print"nickname types:"
        print"  1:  adjective"
        print"  formatting: yourName the randomAdjective"
        print' '
        print"  2:  adjective animal"
        print"  formatting: yourName the randomAdjective randomAnimal"
        print' '
        print"  3:  adjective object"
        print"  formatting: yourName the randomAdjective randomObject"
        print' '
        print"  4:  animal"
        print"  formatting: yourName the randomAnimal"
        print' '
        ask(a, b, c)
    
    #fuction that asks the type of nickname
    def ask(a, b, c):
        type = int(input())
    
        n = nicknameTypes()
    
        things = False
    
        if type == 1:
            things = True
            n.adjective(a, b, c)
    
        if type == 2:
            things = True
            n.adjectiveAnimal(a, b, c)
    
        if type == 3:
            things = True
            n.adjectiveObject(a, b, c)
    
        if type == 4:
            things = True
            n.nameAnimal(a, b, c)
    
        elif things == False:
            print"What was that?"
            ask(allDefiningStuff, animals, objects)
    
        time.sleep(1)
        playAgain(a, b, c)
    
    #start of actually doing things
    print("Hola! I'm a stalker so I know that the date is " + time.strftime("%m/%d/%Y"))
    print"Do you wanna know how I know that?"
    wannaKnow = raw_input()
    
    if wannaKnow == 'yes' or wannaKnow == "Yes":
        print"Because I'm a god"
        time.sleep(1)
    
    if wannaKnow == 'no' or wannaKnow == 'No':
        print'well skrew you too'
        time.sleep(1)
    
    main(allDefiningStuff, animals, objects)
    
    

    external by Sachbearbeiter modified Feb 2, 2015  148  0  2  0

    D8: Theming examples: Theme: New more specific suggestions for the image.html.twig template ... *http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340 **Drupal 8 is still Beta - improvements through API modif...

    D8: Theming examples: Theme: New more specific suggestions for the image.html.twig template ... *http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340 **Drupal 8 is still Beta - improvements through API modifications are possible!: theme.php
    /**
     * Implements hook_theme_suggestions_HOOK_alter().
     */
    function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) {
      $entity = $variables['item']->getEntity();
      $field_name = $variables['item']->getParent()->getName();
      $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name;
    }
    
    

    external by Benny modified Nov 8, 2015  137  0  2  0

    suggestions for ninja gold. it's pretty good as is. just some tips :)

    suggestions for ninja gold. it's pretty good as is. just some tips :): pointers.md
    #### use the right tools
    
    Don't use a try/except clause for checking for a key/value pair and providing a default.  Python has `.get` [builtin](http://www.tutorialspoint.com/python/dictionary_get.htm) for this purpose:
    
    ```python
    # no
    		try: 
    			session['activities_arr']
    		except:
    			session['activities_arr'] = []
    
    # yes
        activities_array = session.get('activities_arr', [])
    ```
      
    Also use the `.format` method for formating strings:
    
    ```python
    # no 
    'You earned ' + str(farm_capital) + ' from the farm! ' + date
    # yes
    'You earned {} from the farm! {}'.format(farm_capital, date)
    ```
    
    
    #### write clean, object-oriented, DRY code
    
    You're repeating yourself a lot in your server.py.  If you ever see yourself repeating the same code more than once, stop and see if there's a different way you can do it without repeating yourself. You also have a many-branched if/else.  If you ever start to have more than a few branches in an if/else, see if you can do some kind of mapping instead.  Your function is also over 50 lines long, which should be a red flag.  Functions should only do **One Thing**.
    
    Also, comment your code more, may seem unnecessary/annoying but get in the habit, you'll appreciate it later when you start building large projects because you won't be able to remember why you wrote old code.
    
    Don't just copy paste this code into your repo.  Read it carefully, and see how it is different from your code, and how it addresses each concern mentioned above.  If you don't understand anything, even if it seems like a little thing, please ask me about it.
    
    ``` python
    def generate_number(action):
        """
        Returns a random number between 10 and 20.  If the action is a 'casino',
        the number may be negative instead
        """
        random_number = random.randrange(10, 20)
        if action == 'casino' and random.randint(0, 1):
            return -1 * random_number
        else:
            return random_number
    
    
    def build_message(action, capital):
        """ Build message for activities_arr """
        date = datetime.now().strftime('(%Y/%m/%d %r)')
        earned_lost = 'earned' if capital > 0 else 'lost'
        if action == 'casino' and capital > 0:
            optional_message = 'BALL OUT! '
        elif capital < 0:
            optional_message = 'HANG YOUR HEAD IN SHAME! '
        else:
            optional_message = ''
        return 'You {} {} from the {}! {} {}'.format(earned_lost,
                                                     capital,
                                                     action,
                                                     optional_message,
                                                     date)
    
    
    @app.route('/')
    def init_root():
        if not session.get('gold'):
            session['gold'] = 0
        return render_template('index.html')
    
    
    @app.route('/money_machine', methods=['POST'])
    def process():
        """ Calculate new gold amount, add message to message array """
        activities_array = session.get('activities_arr', [])
        action = request.form.get('action')
    
        capital = generate_number(action)
        message = build_message(action, capital)
        activities_array.insert(0, message)
    
        session['gold'] += capital
        session['activities_arr'] = activities_array
        return redirect('/')
    ```
    
    #### Couple minor style things:
    Use soft tabs, set your sublime text default to be soft
    
    `(10, 20)` not `(10,20)`
    
    When you have functions that aren't class methods, put two lines between them:
    ```python
    # no
        return render_template('index.html')
    
    @app.route('/money_machine', methods=['POST'])
    
    # yes
    
        return render_template('index.html')
    
    
    @app.route('/money_machine', methods=['POST'])
    ```
    
    Also, do you have GitGutter installed on your sublime text yet?
    
    

    external by lorenzhs modified Sep 2, 2014  125  0  2  0

    GB light theme suggestions // https://github.com/glowing-bear/glowing-bear/pull/434

    GB light theme suggestions // https://github.com/glowing-bear/glowing-bear/pull/434: light.diff
    diff --git a/css/themes/light.css b/css/themes/light.css
    index 3460f6a..833e30d 100644
    --- a/css/themes/light.css
    +++ b/css/themes/light.css
    @@ -4,7 +4,7 @@ body {
     }
     
     #bufferlines {
    -    background-color: #efefef;
    +    background-color: #f5f5f5;
     }
     
     html {
    @@ -41,7 +41,7 @@ li.notification {
     }
     
     ::-webkit-scrollbar-track-piece  {
    -    background-color: black;
    +    background-color: #aaa;
     }
     ::-webkit-scrollbar-thumb:vertical {
         height: 15px;
    @@ -94,30 +94,34 @@ input[type=text], input[type=password], #sendMessage, .badge {
         -webkit-box-shadow: rgba(255, 255, 255, 0.07) 0 1px 0;
         -moz-box-shadow: rgba(255, 255, 255, 0.07) 0 1px 0;
         box-shadow: rgba(255, 255, 255, 0.07) 0 1px 0;
    -    border-bottom: 1px solid #121212;
    +    border-bottom: 1px solid #aaa;
     }
     .vertical-line {
         -webkit-box-shadow: rgba(255, 255, 255, 0.07) 1px 0 0;
         -moz-box-shadow: rgba(255, 255, 255, 0.07) 1px 0 0;
         box-shadow: rgba(255, 255, 255, 0.07) 1px 0 0;
    -    border-right: 1px solid #121212;
    +    border-right: 1px solid #aaa;
     }
     .vertical-line-left {
         -webkit-box-shadow: rgba(255, 255, 255, 0.07) -1px 0 0;
         -moz-box-shadow: rgba(255, 255, 255, 0.07) -1px 0 0;
         box-shadow: rgba(255, 255, 255, 0.07) -1px 0 0;
    -    border-left: 1px solid #121212;
    +    border-left: 1px solid #aaa;
     }
     .panel-group .panel-heading + .panel-collapse .panel-body, .modal-body, .modal-header, .modal-footer {
         -webkit-box-shadow: rgba(255, 255, 255, 0.07) 0 -1px 0;
         -moz-box-shadow: rgba(255, 255, 255, 0.07) 0 -1px 0;
         box-shadow: rgba(255, 255, 255, 0.07) 0 -1px 0;
    -    border-top: 1px solid #121212;
    +    border-top: 1px solid #aaa;
     }
     
     #readmarker {
         border-top-color: rgba(255, 255, 255, 0.3);
    -    border-bottom-color: #121212;
    +    border-bottom-color: #666;
    +}
    +
    +td.prefix {
    +    border-right: 1px solid #aaa;
     }
     
     /****************************/
    @@ -242,7 +246,7 @@ input[type=text], input[type=password], #sendMessage, .badge {
     .cob-chat {
     }
     .cob-chat_time {
    -    color: #999; 
    +    color: #999;
     }
     .cob-chat_time_delimiters {
     }
    @@ -386,7 +390,7 @@ input[type=text], input[type=password], #sendMessage, .badge {
     
     /* WeeChat colors, foreground */
     .cwf-default {
    -    color: #575757;
    +    color: #333;
     }
     
     .cwf-black {
    
    
    

    external by benzittlau modified May 29, 2015  114  0  2  0

    Programatically Accept Suggestions in Google Docs

    Programatically Accept Suggestions in Google Docs: hard_click.js
    function hardClick(node) {
      triggerMouseEvent (node, "mouseover");
      triggerMouseEvent (node, "mousedown");
      triggerMouseEvent (node, "mouseup");
      triggerMouseEvent (node, "click");
    }
    
    function triggerMouseEvent (node, eventType) {
        var clickEvent = document.createEvent ('MouseEvents');
        clickEvent.initEvent (eventType, true, true);
        node.dispatchEvent (clickEvent);
    }
    
    hardClick(document.getElementsByClassName("docos-icon-accept-suggestion-checkmark")[0])
    
    
    
    • Public Snippets
    • Channels Snippets