text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Coverage Report :: BasicAction</title>

    [ all classes ]
    [ net.sf.jabref.gui.plaintextimport ]

Coverage Summary for Class: BasicAction (net.sf.jabref.gui.plaintextimport)

  Class

  Class, %

  Method, %

  Line, %

  BasicAction

    0%

    (0/ 1)

    0%

    (0/ 2)

    0%

    (0/ 5)

1 package net.sf.jabref.gui.plaintextimport;
2
3 import java.awt.BorderLayout;
4 import java.awt.Color;
5 import java.awt.Component;
6 import java.awt.Dimension;
7 import java.awt.Font;
8 import java.awt.GridBagConstraints;
9 import java.awt.GridBagLayout;
10 import java.awt.GridLayout;
11 import java.awt.Insets;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.KeyEvent;
14 import java.awt.event.MouseAdapter;
15 import java.awt.event.MouseEvent;
16 import java.awt.event.MouseListener;
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.io.StringWriter;
21 import java.nio.file.Path;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.Optional;
26
27 import javax.swing.AbstractAction;
28 import javax.swing.Action;
29 import javax.swing.ActionMap;
30 import javax.swing.BorderFactory;
31 import javax.swing.ButtonGroup;
32 import javax.swing.DefaultListCellRenderer;
33 import javax.swing.Icon;
34 import javax.swing.InputMap;
35 import javax.swing.JButton;
36 import javax.swing.JComponent;
37 import javax.swing.JDialog;
38 import javax.swing.JLabel;
39 import javax.swing.JList;
40 import javax.swing.JMenu;
41 import javax.swing.JMenuItem;
42 import javax.swing.JPanel;
43 import javax.swing.JPopupMenu;
44 import javax.swing.JRadioButton;
45 import javax.swing.JScrollPane;
46 import javax.swing.JTabbedPane;
47 import javax.swing.JTextArea;
48 import javax.swing.JTextPane;
49 import javax.swing.JToolBar;
50 import javax.swing.ListSelectionModel;
51 import javax.swing.ScrollPaneConstants;
52 import javax.swing.border.TitledBorder;
53 import javax.swing.event.ListSelectionEvent;
54 import javax.swing.event.ListSelectionListener;
55 import javax.swing.text.BadLocationException;
56 import javax.swing.text.EditorKit;
57 import javax.swing.text.Style;
58 import javax.swing.text.StyleConstants;
59 import javax.swing.text.StyleContext;
60 import javax.swing.text.StyledDocument;
61
62 import net.sf.jabref.Globals;
63 import net.sf.jabref.gui.ClipBoardManager;
64 import net.sf.jabref.gui.EntryMarker;
65 import net.sf.jabref.gui.FileDialog;
66 import net.sf.jabref.gui.IconTheme;
67 import net.sf.jabref.gui.JabRefFrame;
68 import net.sf.jabref.gui.OSXCompatibleToolbar;
69 import net.sf.jabref.gui.keyboard.KeyBinding;
70 import net.sf.jabref.gui.undo.NamedCompound;
71 import net.sf.jabref.gui.util.component.OverlayPanel;
72 import net.sf.jabref.logic.bibtex.BibEntryWriter;
73 import net.sf.jabref.logic.bibtex.LatexFieldFormatter;
74 import net.sf.jabref.logic.importer.ParserResult;
75 import net.sf.jabref.logic.importer.fileformat.FreeCiteImporter;
76 import net.sf.jabref.logic.l10n.Localization;
77 import net.sf.jabref.logic.util.FileExtensions;
78 import net.sf.jabref.logic.util.OS;
79 import net.sf.jabref.logic.util.UpdateField;
80 import net.sf.jabref.model.EntryTypes;
81 import net.sf.jabref.model.entry.BibEntry;
82 import net.sf.jabref.model.entry.EntryType;
83 import net.sf.jabref.model.entry.FieldName;
84 import net.sf.jabref.model.entry.FieldProperty;
85 import net.sf.jabref.model.entry.InternalBibtexFields;
86 import net.sf.jabref.preferences.JabRefPreferences;
87
88 import com.jgoodies.forms.builder.ButtonBarBuilder;
89 import org.apache.commons.logging.Log;
90 import org.apache.commons.logging.LogFactory;
91
92 /**
93  * import from plain text => simple mark/copy/paste into bibtex entry
94  * <p>
95  * TODO
96  * - change colors and fonts
97  * - delete selected text
98  * - make textarea editable
99  * - create several bibtex entries in dialog
100  * - if the dialog works with an existing entry (right click menu item), the cancel option doesn't work well
101  */
102 public class TextInputDialog extends JDialog {
103
104     private static final Log LOGGER = LogFactory.getLog(TextInputDialog.class);
105
106     private final JButton okButton = new JButton(Localization.lang("Accept"));
107     private final JButton cancelButton = new JButton(Localization.lang("Cancel"));
108     private final JButton insertButton = new JButton(Localization.lang("Insert"));
109     private final JButton parseWithFreeCiteButton = new JButton(Localization.lang("Parse with FreeCite"));
110     private final JPanel panel1 = new JPanel();
111     private final JPanel buttons = new JPanel();
112     private final JPanel rawPanel = new JPanel();
113     private final JPanel sourcePanel = new JPanel();
114     private JList<String> fieldList;
115     private final JRadioButton override = new JRadioButton(Localization.lang("Override"));
116     private final JRadioButton append = new JRadioButton(Localization.lang("Append"));
117     private final JToolBar toolBar = new OSXCompatibleToolbar();
118
119     private final List<String> allFields = new ArrayList<>();
120     private final List<String> requiredFields = new ArrayList<>();
121     private final List<String> optionalFields = new ArrayList<>();
122
123     private final BibEntry entry;
124
125     private final JPopupMenu inputMenu = new JPopupMenu();
126     private StyledDocument document; // content from inputPane
127     private final JTextPane textPane = new JTextPane();
128     private final JTextArea sourcePreview = new JTextArea();
129
130     private final TagToMarkedTextStore markedTextStore;
131
132     private final JabRefFrame frame;
133
134     private boolean okPressed;
135
136
137     public TextInputDialog(JabRefFrame frame, BibEntry bibEntry) {
138         super(frame, true);
139
140         this.frame = Objects.requireNonNull(frame);
141
142         entry = Objects.requireNonNull(bibEntry);
143         markedTextStore = new TagToMarkedTextStore();
144
145         jbInit();
146         pack();
147         updateSourceView();
148     }
149
150     private void jbInit() {
151         getContentPane().setLayout(new BorderLayout());
152         StringBuilder typeStr = new StringBuilder("Plain text import");
153         if (entry.getType() != null) {
154             typeStr.append(' ').append(Localization.lang("for")).append(' ').append(entry.getType());
155         }
156
157         this.setTitle(typeStr.toString());
158         getContentPane().add(panel1, BorderLayout.CENTER);
159
160         initRawPanel();
161         initButtonPanel();
162         initSourcePanel();
163
164         JTabbedPane tabbed = new JTabbedPane();
165
166         tabbed.add(rawPanel, Localization.lang("Raw source"));
167         tabbed.add(sourcePanel, Localization.lang("%0 source", frame.getCurrentBasePanel().getBibDatabaseContext().getMode().getFormattedName()));
168
169         // Panel Layout
170         panel1.setLayout(new BorderLayout());
171         panel1.add(tabbed, BorderLayout.CENTER);
172         panel1.add(buttons, BorderLayout.SOUTH);
173
174         // Key bindings:
175         ActionMap am = buttons.getActionMap();
176         InputMap im = buttons.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
177         im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
178         am.put("close", new AbstractAction() {
179
180             @Override
181             public void actionPerformed(ActionEvent e) {
182                 dispose();
183             }
184         });
185     }
186
187     // Panel with text import functionality
188     private void initRawPanel() {
189         rawPanel.setLayout(new BorderLayout());
190
191         // Textarea
192         textPane.setEditable(false);
193
194         document = textPane.getStyledDocument();
195         addStylesToDocument();
196
197         try {
198             document.insertString(0, "", document.getStyle("regular"));
199         } catch (BadLocationException ex) {
200             LOGGER.warn("Problem setting style", ex);
201
202         }
203
204         OverlayPanel testPanel = new OverlayPanel(textPane, Localization.lang("paste text here"));
205
206         testPanel.setPreferredSize(new Dimension(450, 255));
207         testPanel.setMaximumSize(new Dimension(450, Integer.MAX_VALUE));
208
209         // Setup fields (required to be done before setting up popup menu)
210         fieldList = new JList<>(getAllFields());
211         fieldList.setCellRenderer(new SimpleCellRenderer(fieldList.getFont()));
212         ListSelectionModel listSelectionModel = fieldList.getSelectionModel();
213         listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
214         listSelectionModel.addListSelectionListener(new FieldListSelectionHandler());
215         fieldList.addMouseListener(new FieldListMouseListener());
216
217         // After the call to getAllFields
218         initPopupMenuAndToolbar();
219
220         //Add listener to components that can bring up popup menus.
221         MouseListener popupListener = new PopupListener(inputMenu);
222         textPane.addMouseListener(popupListener);
223         testPanel.addMouseListener(popupListener);
224
225         JPanel leftPanel = new JPanel(new BorderLayout());
226
227         leftPanel.add(toolBar, BorderLayout.NORTH);
228         leftPanel.add(testPanel, BorderLayout.CENTER);
229
230         JPanel inputPanel = setUpFieldListPanel();
231
232         // parse with FreeCite button
233         parseWithFreeCiteButton.addActionListener(event -> {
234             if (parseWithFreeCiteAndAddEntries()) {
235                 okPressed = false; // we do not want to have the super method to handle our entries, we do it on our own
236                 dispose();
237             }
238         });
239
240         rawPanel.add(leftPanel, BorderLayout.CENTER);
241         rawPanel.add(inputPanel, BorderLayout.EAST);
242
243         JLabel desc = new JLabel("<html><h3>" + Localization.lang("Plain text import") + "</h3><p>"
244                 + Localization.lang("This is a simple copy and paste dialog. First load or paste some text into "
245                 + "the text input area.<br>After that, you can mark text and assign it to a BibTeX field.")
246                 + "</p></html>");
247         desc.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
248
249         rawPanel.add(desc, BorderLayout.SOUTH);
250     }
251
252     private JPanel setUpFieldListPanel() {
253         JPanel inputPanel = new JPanel();
254
255         // Panel Layout
256         GridBagLayout gbl = new GridBagLayout();
257         GridBagConstraints con = new GridBagConstraints();
258         con.weightx = 0;
259         con.insets = new Insets(5, 5, 0, 5);
260         con.fill = GridBagConstraints.HORIZONTAL;
261
262         inputPanel.setLayout(gbl);
263
264         // Border
265         TitledBorder titledBorder1 = new TitledBorder(BorderFactory.createLineBorder(new Color(153, 153, 153), 2),
266                 Localization.lang("Work options"));
267         inputPanel.setBorder(titledBorder1);
268         inputPanel.setMinimumSize(new Dimension(10, 10));
269
270         JScrollPane fieldScroller = new JScrollPane(fieldList);
271         fieldScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
272
273         // insert buttons
274         insertButton.addActionListener(event -> insertTextForTag(override.isSelected()));
275
276         // Radio buttons
277         append.setToolTipText(Localization.lang("Append the selected text to BibTeX field"));
278         append.setMnemonic(KeyEvent.VK_A);
279         append.setSelected(true);
280
281         override.setToolTipText(Localization.lang("Override the BibTeX field by the selected text"));
282         override.setMnemonic(KeyEvent.VK_O);
283         override.setSelected(false);
284
285         //Group the radio buttons.
286         ButtonGroup group = new ButtonGroup();
287         group.add(append);
288         group.add(override);
289
290         JPanel radioPanel = new JPanel(new GridLayout(0, 1));
291         radioPanel.add(append);
292         radioPanel.add(override);
293
294         // insert sub components
295         JLabel label1 = new JLabel(Localization.lang("Available BibTeX fields"));
296         con.gridwidth = GridBagConstraints.REMAINDER;
297         gbl.setConstraints(label1, con);
298         inputPanel.add(label1);
299
300         con.gridwidth = GridBagConstraints.REMAINDER;
301         con.gridheight = 8;
302         con.weighty = 1;
303         con.fill = GridBagConstraints.BOTH;
304         gbl.setConstraints(fieldScroller, con);
305         inputPanel.add(fieldScroller);
306
307         con.fill = GridBagConstraints.HORIZONTAL;
308         con.weighty = 0;
309         con.gridwidth = 2;
310         gbl.setConstraints(radioPanel, con);
311         inputPanel.add(radioPanel);
312
313         con.gridwidth = GridBagConstraints.REMAINDER;
314         gbl.setConstraints(insertButton, con);
315         inputPanel.add(insertButton);
316         return inputPanel;
317     }
318
319     private void initPopupMenuAndToolbar() {
320         // copy/paste Menu
321         PasteAction pasteAction = new PasteAction();
322         ClearAction clearAction = new ClearAction();
323         JMenuItem pasteMI = new JMenuItem(pasteAction);
324
325         inputMenu.add(clearAction);
326         inputMenu.addSeparator();
327         inputMenu.add(pasteMI);
328         inputMenu.addSeparator();
329
330         // Right-click append/override
331         JMenu appendMenu = new JMenu(Localization.lang("Append"));
332         appendMenu.setToolTipText(Localization.lang("Append the selected text to BibTeX field"));
333         JMenu overrideMenu = new JMenu(Localization.lang("Override"));
334         overrideMenu.setToolTipText(Localization.lang("Override the BibTeX field by the selected text"));
335         for (String field : allFields) {
336             appendMenu.add(new JMenuItem(new MenuTextForTagAction(field, false)));
337             overrideMenu.add(new JMenuItem(new MenuTextForTagAction(field, true)));
338         }
339
340         inputMenu.add(appendMenu);
341         inputMenu.add(overrideMenu);
342
343         // Toolbar
344
345         toolBar.add(clearAction);
346         toolBar.setBorderPainted(false);
347         toolBar.addSeparator();
348         toolBar.add(pasteAction);
349         toolBar.add(new LoadAction());
350     }
351
352     private void initButtonPanel() {
353         okButton.addActionListener(event -> {
354             okPressed = true;
355             dispose();
356         });
357         cancelButton.addActionListener(event -> dispose());
358
359         ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
360         buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
361         bb.addGlue();
362         bb.addButton(okButton);
363         bb.addButton(parseWithFreeCiteButton);
364         bb.addButton(cancelButton);
365         bb.addGlue();
366     }
367
368     // Panel with BibTeX source code
369     private void initSourcePanel() {
370         sourcePreview.setEditable(false);
371         sourcePreview.setFont(new Font("Monospaced", Font.PLAIN, Globals.prefs.getInt(JabRefPreferences.FONT_SIZE)));
372         JScrollPane paneScrollPane = new JScrollPane(sourcePreview);
373         paneScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
374         paneScrollPane.setPreferredSize(new Dimension(500, 255));
375         paneScrollPane.setMinimumSize(new Dimension(10, 10));
376
377         sourcePanel.setLayout(new BorderLayout());
378         sourcePanel.add(paneScrollPane, BorderLayout.CENTER);
379     }
380
381     private void addStylesToDocument() {
382         //Initialize some styles.
383         Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
384
385         Style regularStyle = document.addStyle("regular", defaultStyle);
386         StyleConstants.setFontFamily(defaultStyle, "SansSerif");
387         StyleConstants.setFontSize(defaultStyle, Globals.prefs.getInt(JabRefPreferences.FONT_SIZE));
388
389         Style s = document.addStyle("used", regularStyle);
390         StyleConstants.setBold(s, true);
391         StyleConstants.setForeground(s, Color.blue);
392
393         s = document.addStyle("marked", regularStyle);
394         StyleConstants.setBold(s, true);
395         StyleConstants.setForeground(s, Color.red);
396     }
397
398     private void insertTextForTag(boolean overrideField) {
399         String fieldName = fieldList.getSelectedValue();
400         if (fieldName != null) {
401             String txt = textPane.getSelectedText();
402
403             if (txt != null) {
404                 int selectionStart = textPane.getSelectionStart();
405                 int selectionEnd = textPane.getSelectionEnd();
406
407                 // unselect text
408                 textPane.setSelectionEnd(selectionStart);
409
410                 // mark the selected text as "used"
411                 document.setCharacterAttributes(selectionStart, selectionEnd - selectionStart,
412                         document.getStyle("marked"), true);
413
414                 // override an existing entry
415                 if (overrideField) {
416                     entry.setField(fieldName, txt);
417                     // erase old text selection
418                     markedTextStore.setStyleForTag(fieldName, "regular", document); // delete all previous styles
419                     markedTextStore.insertPosition(fieldName, selectionStart, selectionEnd); // insert new selection style
420                 } else {
421                     // memorize the selection for text highlighting
422                     markedTextStore.appendPosition(fieldName, selectionStart, selectionEnd);
423
424                     // get old text from BibTeX tag
425                     Optional<String> old = entry.getField(fieldName);
426
427                     // merge old and selected text
428                     if (old.isPresent()) {
429                         // insert a new name with an additional "and"
430                         if (InternalBibtexFields.getFieldProperties(fieldName).contains(FieldProperty.PERSON_NAMES)) {
431                             entry.setField(fieldName, old.get() + " and " + txt);
432                         } else if (FieldName.KEYWORDS.equals(fieldName)) {
433                             // Add keyword
434                             entry.addKeyword(txt, Globals.prefs.getKeywordDelimiter());
435                         } else {
436                             entry.setField(fieldName, old.get() + txt);
437                         }
438                     } else {
439                         // "null"+"txt" Strings forbidden
440                         entry.setField(fieldName, txt);
441                     }
442                 }
443                 // make the new data in BibTeX source code visible
444                 updateSourceView();
445             }
446         }
447     }
448
449     public boolean okPressed() {
450         return okPressed;
451     }
452
453     /**
454      * tries to parse the pasted reference with freecite
455      *
456      * @return true if successful, false otherwise
457      */
458     private boolean parseWithFreeCiteAndAddEntries() {
459         FreeCiteImporter fimp = new FreeCiteImporter(Globals.prefs.getImportFormatPreferences());
460         String text = textPane.getText();
461
462         // we have to remove line breaks (but keep empty lines)
463         // otherwise, the result is broken
464         text = text.replace(OS.NEWLINE.concat(OS.NEWLINE), "##NEWLINE##");
465         // possible URL line breaks are removed completely.
466         text = text.replace("/".concat(OS.NEWLINE), "/");
467         text = text.replace(OS.NEWLINE, " ");
468         text = text.replace("##NEWLINE##", OS.NEWLINE);
469
470         ParserResult importerResult = fimp.importEntries(text);
471         if (importerResult.hasWarnings()) {
472             frame.showMessage(importerResult.getErrorMessage());
473         }
474         List<BibEntry> importedEntries = importerResult.getDatabase().getEntries();
475         if (importedEntries.isEmpty()) {
476             return false;
477         } else {
478             UpdateField.setAutomaticFields(importedEntries, false, false, Globals.prefs.getUpdateFieldPreferences());
479             boolean markEntries = EntryMarker.shouldMarkEntries();
480
481             for (BibEntry e : importedEntries) {
482                 if (markEntries) {
483                     EntryMarker.markEntry(entry, EntryMarker.IMPORT_MARK_LEVEL, false, new NamedCompound(""));
484                 }
485
486                 frame.getCurrentBasePanel().insertEntry(e);
487             }
488             return true;
489         }
490     }
491
492     // update the bibtex source view and available List
493     private void updateSourceView() {
494         StringWriter sw = new StringWriter(200);
495         try {
496             new BibEntryWriter(new LatexFieldFormatter(Globals.prefs.getLatexFieldFormatterPreferences()),
497                     false).write(entry, sw, frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
498             sourcePreview.setText(sw.getBuffer().toString());
499         } catch (IOException ex) {
500             LOGGER.error("Error in entry" + ": " + ex.getMessage(), ex);
501         }
502
503         fieldList.clearSelection();
504     }
505
506     private String[] getAllFields() {
507         Optional<EntryType> type = EntryTypes.getType(entry.getType(),
508                 frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
509         if (type.isPresent()) {
510             allFields.addAll(type.get().getAllFields());
511             requiredFields.addAll(type.get().getRequiredFieldsFlat());
512             optionalFields.addAll(type.get().getPrimaryOptionalFields());
513         }
514         for (String field : InternalBibtexFields.getAllPublicFieldNames()) {
515             if (!allFields.contains(field)) {
516                 allFields.add(field);
517             }
518         }
519         return allFields.toArray(new String[allFields.size()]);
520     }
521
522
523     private class PasteAction extends BasicAction {
524
525         public PasteAction() {
526             super(Localization.lang("Paste"), Localization.lang("Paste from clipboard"),
527                     IconTheme.JabRefIcon.PASTE.getIcon());
528         }
529
530         @Override
531         public void actionPerformed(ActionEvent e) {
532             String data = new ClipBoardManager().getClipboardContents();
533             int selStart = textPane.getSelectionStart();
534             int selEnd = textPane.getSelectionEnd();
535             if ((selEnd - selStart) > 0) {
536                 textPane.replaceSelection("");
537             }
538             int cPos = textPane.getCaretPosition();
539             try {
540                 document.insertString(cPos, data, document.getStyle("regular"));
541             } catch (BadLocationException ex) {
542                 LOGGER.warn("Could not paste text", ex);
543             }
544         }
545     }
546
547     private class LoadAction extends BasicAction {
548
549         public LoadAction() {
550             super(Localization.lang("Open"), Localization.lang("Open file"), IconTheme.JabRefIcon.OPEN.getIcon());
551         }
552
553         @Override
554         public void actionPerformed(ActionEvent e) {
555             try {
556                 FileDialog dialog = new FileDialog(frame).withExtension(FileExtensions.TXT);
557                 dialog.setDefaultExtension(FileExtensions.TXT);
558                 Optional<Path> path = dialog.showDialogAndGetSelectedFile();
559
560                 if (path.isPresent()) {
561                     File newFile = path.get().toFile();
562                     document.remove(0, document.getLength());
563                     EditorKit eKit = textPane.getEditorKit();
564                     if (eKit != null) {
565                         try (FileInputStream fis = new FileInputStream(newFile)) {
566                             eKit.read(fis, document, 0);
567                             document.setLogicalStyle(0, document.getStyle("regular"));
568                         }
569                     }
570                 }
571             } catch (BadLocationException | IOException ex) {
572                 LOGGER.warn("Problem reading or inserting file", ex);
573             }
574         }
575     }
576
577     private class ClearAction extends BasicAction {
578
579         public ClearAction() {
580             super(Localization.lang("Clear"), Localization.lang("Clear inputarea"), IconTheme.JabRefIcon.NEW.getIcon());
581         }
582
583         @Override
584         public void actionPerformed(ActionEvent e) {
585             textPane.setText("");
586         }
587     }
588
589     class FieldListSelectionHandler implements ListSelectionListener {
590
591         private int lastIndex = -1;
592
593
594         @Override
595         public void valueChanged(ListSelectionEvent e) {
596             ListSelectionModel lsm = (ListSelectionModel) e.getSource();
597
598             int index = lsm.getAnchorSelectionIndex();
599             if (index != lastIndex) {
600                 boolean isAdjusting = e.getValueIsAdjusting();
601
602                 if (!isAdjusting) {
603                     if (lastIndex > -1) {
604                         String tag1 = fieldList.getModel().getElementAt(lastIndex);
605                         markedTextStore.setStyleForTag(tag1, "used", document);
606                     }
607
608                     String tag2 = fieldList.getModel().getElementAt(index);
609                     markedTextStore.setStyleForTag(tag2, "marked", document);
610
611                     lastIndex = index;
612                 }
613             }
614         }
615     }
616
617     // simple JList Renderer
618     // based on : Advanced JList Programming at developers.sun.com
619     private class SimpleCellRenderer extends DefaultListCellRenderer {
620
621         private final Font baseFont;
622         private final Font usedFont;
623         private final Icon okIcon = IconTheme.JabRefIcon.PLAIN_TEXT_IMPORT_DONE.getSmallIcon();
624         private final Icon needIcon = IconTheme.JabRefIcon.PLAIN_TEXT_IMPORT_TODO.getSmallIcon();
625         private final Color requiredColor = Globals.prefs.getColor(JabRefPreferences.TABLE_REQ_FIELD_BACKGROUND);
626         private final Color optionalColor = Globals.prefs.getColor(JabRefPreferences.TABLE_OPT_FIELD_BACKGROUND);
627
628
629         public SimpleCellRenderer(Font normFont) {
630             baseFont = normFont;
631             usedFont = baseFont.deriveFont(Font.ITALIC);
632         }
633
634         /* This is the only method defined by ListCellRenderer.  We just
635          * reconfigure the Jlabel each time we're called.
636          */
637         @Override
638         public Component getListCellRendererComponent(JList<?> list, Object value, // value to display
639                                                       int index, // cell index
640                                                       boolean iss, // is the cell selected
641                                                       boolean chf) // the list and the cell have the focus
642         {
643             /* The DefaultListCellRenderer class will take care of
644              * the JLabels text property, it's foreground and background
645              * colors, and so on.
646              */
647             super.getListCellRendererComponent(list, value, index, iss, chf);
648
649             /* We additionally set the JLabels icon property here.
650              */
651             String s = value.toString();
652             if (entry.hasField(s)) {
653                 this.setForeground(Color.gray);
654                 this.setFont(usedFont);
655                 this.setIcon(okIcon);
656                 this.setToolTipText(Localization.lang("Filled"));
657             } else {
658                 this.setIcon(needIcon);
659                 this.setToolTipText(Localization.lang("Field is missing"));
660             }
661             if (requiredFields.contains(s)) {
662                 this.setBackground(requiredColor);
663             } else if (optionalFields.contains(s)) {
664                 this.setBackground(optionalColor);
665             }
666             return this;
667         }
668     }
669
670     private class FieldListMouseListener extends MouseAdapter {
671
672         @Override
673         public void mouseClicked(MouseEvent e) {
674             if (e.getClickCount() == 2) {
675                 insertTextForTag(override.isSelected());
676             }
677         }
678     }
679
680     private class MenuTextForTagAction extends AbstractAction {
681
682         private final String field;
683         private final Boolean overrideField;
684
685
686         public MenuTextForTagAction(String field, Boolean overrideField) {
687             super(field);
688             this.field = field;
689             this.overrideField = overrideField;
690         }
691
692         @Override
693         public void actionPerformed(ActionEvent e) {
694             // To enable correct marking of used values
695             fieldList.setSelectedValue(field, false);
696             insertTextForTag(overrideField);
697         }
698     }
699 }
700
701 class PopupListener extends MouseAdapter {
702
703     private final JPopupMenu popMenu;
704
705
706     public PopupListener(JPopupMenu menu) {
707         popMenu = menu;
708     }
709
710     @Override
711     public void mousePressed(MouseEvent e) {
712         maybeShowPopup(e);
713     }
714
715     @Override
716     public void mouseReleased(MouseEvent e) {
717         maybeShowPopup(e);
718     }
719
720     private void maybeShowPopup(MouseEvent e) {
721         if (e.isPopupTrigger()) {
722             popMenu.show(e.getComponent(), e.getX(), e.getY());
723         }
724     }
725 }
726
727 abstract class BasicAction extends AbstractAction {
728
729     public BasicAction(String text, String description, Icon icon) {
730         super(text, icon);
731         putValue(Action.SHORT_DESCRIPTION, description);
732     }
733
734     public BasicAction(String text) {
735         super(text);
736     }
737
738     @Override
739     public abstract void actionPerformed(ActionEvent e);
740 }

generated on 2017-07-15 00:44


text:
package com.topie.dict.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.topie.api.tenant.TenantHolder;

import com.topie.core.export.Exportor;
import com.topie.core.export.TableModel;
import com.topie.core.mapper.BeanMapper;
import com.topie.core.page.Page;
import com.topie.core.query.PropertyFilter;
import com.topie.core.spring.MessageHelper;

import com.topie.dict.persistence.domain.DictSchema;
import com.topie.dict.persistence.manager.DictSchemaManager;
import com.topie.dict.persistence.manager.DictTypeManager;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("dict")
public class DictSchemaController {
    private DictSchemaManager dictSchemaManager;
    private DictTypeManager dictTypeManager;
    private BeanMapper beanMapper = new BeanMapper();
    private MessageHelper messageHelper;
    private Exportor exportor;
    private TenantHolder tenantHolder;

    @RequestMapping("dict-schema-config")
    public String config(@RequestParam("typeId") Long typeId, Model model) {
        String hql = "from DictSchema where dictType.id=? order by priority";
        List<DictSchema> dictSchemas = dictSchemaManager.find(hql, typeId);

        model.addAttribute("dictSchemas", dictSchemas);

        return "dict/dict-schema-config";
    }

    @RequestMapping("dict-schema-list")
    public String list(@ModelAttribute Page page,
            @RequestParam Map<String, Object> parameterMap, Model model) {
        String tenantId = tenantHolder.getTenantId();
        List<PropertyFilter> propertyFilters = PropertyFilter
                .buildFromMap(parameterMap);
        propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
        page = dictSchemaManager.pagedQuery(page, propertyFilters);

        model.addAttribute("page", page);

        return "dict/dict-schema-list";
    }

    @RequestMapping("dict-schema-input")
    public String input(@RequestParam(value = "id", required = false) Long id,
            Model model) {
        if (id != null) {
            DictSchema dictSchema = dictSchemaManager.get(id);
            model.addAttribute("model", dictSchema);
        }

        return "dict/dict-schema-input";
    }

    @RequestMapping("dict-schema-save")
    public String save(@ModelAttribute DictSchema dictSchema,
            @RequestParam("typeId") Long typeId,
            RedirectAttributes redirectAttributes) {
        String tenantId = tenantHolder.getTenantId();
        DictSchema dest = null;

        Long id = dictSchema.getId();

        if (id != null) {
            dest = dictSchemaManager.get(id);
            beanMapper.copy(dictSchema, dest);
        } else {
            dest = dictSchema;
            dest.setTenantId(tenantId);
        }

        dest.setDictType(dictTypeManager.get(typeId));

        dictSchemaManager.save(dest);

        messageHelper.addFlashMessage(redirectAttributes, "core.success.save",
                "保存成功");

        return "redirect:/dict/dict-schema-config.do?typeId=" + typeId;
    }

    @RequestMapping("dict-schema-remove")
    public String remove(@RequestParam("selectedItem") List<Long> selectedItem,
            @RequestParam("typeId") Long typeId,
            RedirectAttributes redirectAttributes) {
        List<DictSchema> dictSchemas = dictSchemaManager
                .findByIds(selectedItem);

        dictSchemaManager.removeAll(dictSchemas);

        messageHelper.addFlashMessage(redirectAttributes,
                "core.success.delete", "删除成功");

        return "redirect:/dict/dict-schema-config.do?typeId=" + typeId;
    }

    @RequestMapping("dict-schema-export")
    public void export(@ModelAttribute Page page,
            @RequestParam Map<String, Object> parameterMap,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String tenantId = tenantHolder.getTenantId();
        List<PropertyFilter> propertyFilters = PropertyFilter
                .buildFromMap(parameterMap);
        propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
        page = dictSchemaManager.pagedQuery(page, propertyFilters);

        List<DictSchema> dictSchemas = (List<DictSchema>) page.getResult();

        TableModel tableModel = new TableModel();
        tableModel.setName("dict info");
        tableModel.addHeaders("id", "name", "stringValue", "description");
        tableModel.setData(dictSchemas);
        exportor.export(request, response, tableModel);
    }

    // ~ ======================================================================
    @Resource
    public void setDictSchemaManager(DictSchemaManager dictSchemaManager) {
        this.dictSchemaManager = dictSchemaManager;
    }

    @Resource
    public void setDictTypeManager(DictTypeManager dictTypeManager) {
        this.dictTypeManager = dictTypeManager;
    }

    @Resource
    public void setExportor(Exportor exportor) {
        this.exportor = exportor;
    }

    @Resource
    public void setMessageHelper(MessageHelper messageHelper) {
        this.messageHelper = messageHelper;
    }

    @Resource
    public void setTenantHolder(TenantHolder tenantHolder) {
        this.tenantHolder = tenantHolder;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Web.Mvc;
using BookLibrary.Domain;
using BookLibrary.Domain.Entities;
using BookLibrary.ViewModels;

namespace BookLibrary.Controllers
{
	public class BooksController : Controller
	{
		private readonly IBooksRepository booksRepository;

		public BooksController(IBooksRepository booksRepository)
		{
			this.booksRepository = booksRepository;
		}

		public ViewResult Index()
		{
			return View(booksRepository.List());
		}

		public ActionResult Create(CreateBook createBook)
		{
			if(!ModelState.IsValid)
			{
				return View(createBook);
			}

			booksRepository.Save(new Book{ Title = createBook.Title });

			return RedirectToAction("Index");
		}

		[HttpGet]
		public ViewResult Create()
		{
			return View("");
		}

	    public ActionResult Delete(int id)
	    {
	        booksRepository.Delete(id);

	        return RedirectToAction("Index");
	    }
	}
}


text:
package com.aniruddhc.xPlod.ui.adapters.grid;

import static com.aniruddhc.xPlod.Constants.TYPE_ALBUM;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore.Audio.AlbumColumns;

import com.aniruddhc.xPlod.helpers.utils.MusicUtils;
import com.aniruddhc.xPlod.ui.adapters.base.GridViewAdapter;

public class AlbumAdapter extends GridViewAdapter {

    public AlbumAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }

    public void setupViewData(Cursor mCursor){

    	mLineOneText = mCursor.getString(mCursor.getColumnIndexOrThrow(AlbumColumns.ALBUM));
        mLineTwoText = mCursor.getString(mCursor.getColumnIndexOrThrow(AlbumColumns.ARTIST));
        mGridType = TYPE_ALBUM;
        mImageData =  new String[]{ mCursor.getString(mCursor.getColumnIndexOrThrow(BaseColumns._ID)) , mLineTwoText, mLineOneText };
        mPlayingId = MusicUtils.getCurrentAlbumId();
        mCurrentId = mCursor.getLong(mCursor.getColumnIndexOrThrow(BaseColumns._ID));

    }
}


text:
from sklearn2sql_heroku.tests.regression import generic as reg_gen

reg_gen.test_model("SGDRegressor" , "california_housing" , "mssql")


text:
@interface RFWebResponse : NSManagedObject

@property (nonatomic, retain) NSString * eTag;
@property (nonatomic, retain) NSDate * expirationDate;
@property (nonatomic, retain) NSData * requestBodyData;
@property (nonatomic, retain) NSString * requestURL;
@property (nonatomic, retain) NSData * response;
@property (nonatomic, retain) NSData * responseBodyData;
@property (nonatomic, retain) NSDecimalNumber * urlHash;
@property (nonatomic, retain) NSString * lastModified;
@property (nonatomic, retain) NSString * cacheIdentifier;

@end


text:
{-# LANGUAGE StandaloneDeriving, TypeOperators, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances #-}

-- Experimenting with Data types à la carte
-- http://www.cs.ru.nl/~W.Swierstra/Publications/DataTypesALaCarte.pdf
module ALaCarte where

import Data.Monoid
import Data.Proxy (Proxy(..))
import Data.Union
import Data.Functor.Classes

-- Expressions parameterized by the signature of the expression constructor.
newtype Expr f = In (f (Expr f))

deriving instance Show (f (Expr f)) => Show (Expr f)

-- Smart constructor helper
inject :: (g :< f) => g (Expr (Union f)) -> Expr (Union f)
inject = In . inj

-- Result of evaluating, checking, infering...
type Result = Either String

-- Example usage:
-- λ let x :: ALaCarte.Expr (Union '[Val, Add, Mul]) = val 80 ⓧ  val 5 ⊕ val 3
-- λ ALaCarte.eval x
-- 403
-- λ ALaCarte.pretty x
-- "((80 * 5) + 3)"

-- Specific expression data types (these are the à la carte data types).
-- newtype Val e = Val Int deriving (Functor)
-- instance Eval Val where
--   evalAlgebra (Val x) = x
-- instance Render Val where
--   render (Val x) = show x
--
-- data Add e = Add e e deriving (Functor)
-- instance Eval Add where
--   evalAlgebra (Add x y) = x + y
-- instance Render Add where
--   render (Add x y) = "(" <> pretty x <> " + " <> pretty y <> ")"
--
-- data Mul x = Mul x x  deriving (Functor)
-- instance Eval Mul where
--   evalAlgebra (Mul x y) = x * y
-- instance Render Mul where
--   render (Mul x y) = "(" <> pretty x <> " * " <> pretty y <> ")"

-- Smart constructors
-- val :: (Val :< f) => Int -> Expr (Union f)
-- val = inject . Val
--
-- infixl 6 ⊕
-- (⊕) :: (Add :< f) => Expr (Union f) -> Expr (Union f) -> Expr (Union f)
-- x ⊕ y = inject (Add x y)
--
-- infixl 7 ⓧ
-- (ⓧ) :: (Mul :< f) => Expr (Union f) -> Expr (Union f) -> Expr (Union f)
-- x ⓧ y = inject (Mul x y)


text:
const m = new Map();
If you wish to populate the Map when it is initialized, the constructor optionally accepts an iterable object, expecting it to contain key/value pair arrays. Each pair in the iterable argument will be inserted into the newly created Map in the order in which they are iterated:
// Initialize map with nested arrays
const m1 = new Map([
  ["key1", "val1"],
  ["key2", "val2"],
  ["key3", "val3"]
]);
alert(m1.size);  // 3

// Initialize map with custom-defined iterator
const m2 = new Map({
  [Symbol.iterator]: function*() {
    yield ["key1", "val1"];
    yield ["key2", "val2"];
    yield ["key3", "val3"];
  }
});
alert(m2.size);  // 3

// Map expects values to be key/value whether they are provided or not
const m3 = new Map([[]]);
alert(m3.has(undefined));  // true
alert(m3.get(undefined));  // undefined


text:
typedef struct StringTokenScanner {
    TokenScanner token_scanner;
    const wchar_t* source;
    int line;
    int pos;
} StringTokenScanner;

static Token* StringTokenScanner_read(TokenScanner* token_scanner);

static void StringTokenScanner_delete(TokenScanner* token_scanner);

TokenScanner* StringTokenScanner_new(const wchar_t* source) {
    StringTokenScanner* token_scanner = (StringTokenScanner*)malloc(sizeof(StringTokenScanner));
    token_scanner->token_scanner.read = &StringTokenScanner_read;
    token_scanner->token_scanner.delete = &StringTokenScanner_delete;
    token_scanner->source = source;
    token_scanner->line = 0;
    token_scanner->pos = 0;
    return (TokenScanner*) token_scanner;
}

static Token* StringTokenScanner_read(TokenScanner* token_scanner) {
    StringTokenScanner* string_token_scanner = (StringTokenScanner*)token_scanner;
    ++string_token_scanner->line;
    if (!string_token_scanner->source)
        return Token_new(0, string_token_scanner->line);
    if (string_token_scanner->source[string_token_scanner->pos] == L'\0')
        return Token_new(0, string_token_scanner->line);
    int length = 0;
    wchar_t c;
    do {
        c = string_token_scanner->source[string_token_scanner->pos + length++];
    } while (c != L'\0' && c != L'\n' && c != L'\r');
    const GherkinLine* line;
    if (c != L'\0' || length > 1) {
        wchar_t* text = StringUtilities_copy_string_part(string_token_scanner->source + string_token_scanner->pos, length - 1);
        string_token_scanner->pos += length;
        line = GherkinLine_new(text, string_token_scanner->line);
    }
    else
        line = (GherkinLine*)0;
    if (c == L'\r' && string_token_scanner->source[string_token_scanner->pos] == L'\n') {
        string_token_scanner->pos++;
    }
    if (c == L'\0') {
        string_token_scanner->pos--;
    }
    return Token_new(line, string_token_scanner->line);
}

static void StringTokenScanner_delete(TokenScanner* token_scanner) {
    if (!token_scanner) {
        return;
    }
    StringTokenScanner* string_token_scanner = (StringTokenScanner*)token_scanner;
    free((void*)string_token_scanner);
}


text:
<?php
if(!defined('BASEPATH')) die('Dont try to access it directly you maroon.');

class PermsModel extends CI_Model {
    public function __construct() {
        parent::__construct();
    }

    public function getPerms() {
        $q = $this->db->get('permissions');

        if($q->num_rows() > 0)
            return $q->result();

        $q->free_result();
    }

    public function getPermById($id) {
        $this->db->where('ID' , $id);
        $q = $this->db->get('permissions');

        if($q->num_rows() > 0)
            return $q->row();

        $q->free_result();
    }

    /**
     * add / edit permission
     */
    public function savePerm() {
        $strSQL = sprintf("REPLACE INTO `permissions` SET `ID` = %u, `permName` = '%s', `permKey` = '%s'", $_POST['permID'], $_POST['permName'], $_POST['permKey']);
        $this->db->query($strSQL);
    }

    /**
     * delete permission
     */
    public function delPerm() {
        $strSQL = sprintf("DELETE FROM `permissions` WHERE `ID` = %u LIMIT 1", $_POST['permID']);
        mysql_query($strSQL);
    }
}
?>


text:
package io.appium.java_client.android;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;

import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import org.junit.Before;
import org.junit.Test;

public class AndroidSearchingTest extends BaseAndroidTest {

    @Before
    public void setup() throws Exception {
        Activity activity = new Activity("io.appium.android.apis", ".ApiDemos");
        driver.startActivity(activity);
    }

    @Test  public void findByAccessibilityIdTest() {
        assertNotEquals(driver.findElement(MobileBy.AccessibilityId("Graphics")).getText(), null);
        assertEquals(driver.findMElements(MobileBy.AccessibilityId("Graphics")).size(), 1);
    }

    @Test  public void findByAndroidUIAutomatorTest() {
        assertNotEquals(driver
                .findElement(MobileBy
                .AndroidUIAutomator("new UiSelector().clickable(true)")).getText(), null);
        assertNotEquals(driver
                .findMElements(MobileBy
                .AndroidUIAutomator("new UiSelector().clickable(true)")).size(), 0);
        assertNotEquals(driver
                .findMElements(MobileBy
                .AndroidUIAutomator("new UiSelector().clickable(true)")).size(), 1);
    }

    @Test public void findByXPathTest() {
        String byXPath = "//android.widget.TextView[contains(@text, 'Animat')]";
        assertNotNull(driver.findElementByXPath(byXPath).getText());
        assertEquals(driver.findMElementsByXPath(byXPath).size(), 1);
    }

    @Test public void findScrollable() {
        driver.findElementByAccessibilityId("Views").click();
        MobileElement radioGroup = driver
                .findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()"
                + ".resourceId(\"android:id/list\")).scrollIntoView("
                + "new UiSelector().text(\"Radio Group\"));");
        assertNotNull(radioGroup.getLocation());
    }
}


text:
using NguyenAnNinhConfession.ViewModels;
using Windows.UI.Xaml.Controls;

namespace NguyenAnNinhConfession.AppFlyouts
{
    public sealed partial class PrivacyFlyout : SettingsFlyout
    {
        public PrivacyViewModel PrivacyViewModel { get; private set; }
        public PrivacyFlyout()
        {
            this.InitializeComponent();
            PrivacyViewModel = new PrivacyViewModel();
            this.DataContext = this;
        }
    }
}


text:
package com.jetbrains.rest.psi;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.NlsSafe;
import com.jetbrains.rest.validation.RestElementVisitor;
import org.jetbrains.annotations.NotNull;

/**
 * User : catherine
 */
public class RestRole extends RestElement {
  public RestRole(@NotNull final ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    return "RestRole:" + getNode().getElementType().toString();
  }

  public @NlsSafe String getRoleName() {
    String text = getNode().getText();
    return text.substring(1, text.length()-1);
  }

  @Override
  protected void acceptRestVisitor(RestElementVisitor visitor) {
    visitor.visitRole(this);
  }
}


text:
#include "config.h"
#include "DefaultFullScreenVideoHandler.h"

#if USE(QT_MULTIMEDIA)

#include "FullScreenVideoWidget.h"

using namespace WebKit;

bool DefaultFullScreenVideoHandler::s_shouldForceFullScreenVideoPlayback = false;

DefaultFullScreenVideoHandler::DefaultFullScreenVideoHandler()
    : QWebFullScreenVideoHandler()
    , m_fullScreenWidget(new FullScreenVideoWidget)
{
    connect(m_fullScreenWidget, SIGNAL(didExitFullScreen()), this, SIGNAL(fullScreenClosed()));
    m_fullScreenWidget->hide();

    m_fullScreenWidget->close();
}

DefaultFullScreenVideoHandler::~DefaultFullScreenVideoHandler()
{
    delete m_fullScreenWidget;
}

bool DefaultFullScreenVideoHandler::requiresFullScreenForVideoPlayback() const
{
    static bool initialized = false;
    if (!initialized) {
        QByteArray forceFullScreen = qgetenv("QT_WEBKIT_FORCE_FULLSCREEN_VIDEO");
        if (!forceFullScreen.isEmpty())
            s_shouldForceFullScreenVideoPlayback = true;

        initialized = true;
    }

    return s_shouldForceFullScreenVideoPlayback;
}

void DefaultFullScreenVideoHandler::enterFullScreen(QMediaPlayer* player)
{
    m_fullScreenWidget->show(player);
}

void DefaultFullScreenVideoHandler::exitFullScreen()
{
    m_fullScreenWidget->close();
}
#endif


text:
function start() {

    function qsa(item) {
        return document.querySelectorAll(item);
    };

	qsa('#gridHolder')[0].gridOut({
		showGridLines: true,
		movables: '.widget'
	});

	function addElement() {
		qsa('#gridHolder').append("

")
	};
};


text:
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
  <title>NetLog Viewer Tests: loading...</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <link rel="shortcut icon" href="data:image/x-icon;base64,"
        type="image/x-icon">

  <script src="/components/webcomponentsjs/webcomponents.js"></script>
  <script src="/netlog_viewer/net_constants.js"></script>
  <script src="/netlog_viewer/net_internals_test.js"></script>

  <link rel="import" href="/components/polymer/polymer.html">
  <link rel="import" href="/tracing/base/unittest/interactive_test_runner.html">
  <link rel="import" href="/tracing/core/test_utils.html">

  <link rel="import" href="/netlog_viewer/netlog_viewer.html">

  <style>
    html, body {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      overflow: hidden;
      margin: 0px;
    }
  </style>
</head>
<body>
  <script>
    'use strict';

    var globalNetLogViewerElementForTests = null;

    window.addEventListener('load', function() {
      // TODO(rayraymond): The following creates the custom element that
      // represents the entire web app. In the future each test file should
      // import and create its corresponding component to test. For now
      // this uber component can be created at the beginning and all the test
      // files can use it.
      globalNetLogViewerElementForTests =
          document.createElement('netlog-viewer');

      tr.b.unittest.loadAndRunTests({
        title: 'All NetLog Viewer Tests',
        getAllSuiteRelPathsAsync: function() {
          return tr.b.getAsync('/netlog_viewer/tests').then(function(json) {
            return JSON.parse(json).test_relpaths;
          }).catch(function(e) {
           throw e;
          });
        },
        testLinks: []
      });
    });

  </script>
</body>
</html>


text:
"""
Bootstrapper for test framework plugins.

The entire rationale for this system is to get the modules in plugin/
imported without importing all of the supporting library, so that we can
set up things for testing before coverage starts.

The rationale for all of plugin/ being *in* the supporting library in the
first place is so that the testing and plugin suite is available to other
libraries, mainly external SQLAlchemy and Alembic dialects, to make use
of the same test environment and standard suites available to
SQLAlchemy/Alembic themselves without the need to ship/install a separate
package outside of SQLAlchemy.

"""

import importlib.util
import os
import sys

bootstrap_file = locals()["bootstrap_file"]
to_bootstrap = locals()["to_bootstrap"]

def load_file_as_module(name):
    path = os.path.join(os.path.dirname(bootstrap_file), "%s.py" % name)

    spec = importlib.util.spec_from_file_location(name, path)
    assert spec is not None
    assert spec.loader is not None
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod

if to_bootstrap == "pytest":
    sys.modules["sqla_plugin_base"] = load_file_as_module("plugin_base")
    sys.modules["sqla_plugin_base"].bootstrapped_as_sqlalchemy = True
    sys.modules["sqla_pytestplugin"] = load_file_as_module("pytestplugin")
else:
    raise Exception("unknown bootstrap: %s" % to_bootstrap)  # noqa


text:
//
//  File: %p-file.c
//  Summary: "file port interface"
//  Section: ports
//  Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
//  Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2017 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//=////////////////////////////////////////////////////////////////////////=//
//

#include "sys-core.h"

#include "file-req.h"

#define MAX_READ_MASK 0x7FFFFFFF // max size per chunk

//
//  Setup_File: C
//
// Convert native action refinements to file modes.
//
static void Setup_File(REBREQ *file, REBFLGS flags, REBVAL *path)
{
    struct rebol_devreq *req = Req(file);

    if (flags & AM_OPEN_WRITE)
        req->modes |= RFM_WRITE;
    if (flags & AM_OPEN_READ)
        req->modes |= RFM_READ;
    if (flags & AM_OPEN_SEEK)
        req->modes |= RFM_SEEK;

    if (flags & AM_OPEN_NEW) {
        req->modes |= RFM_NEW;
        if (not (flags & AM_OPEN_WRITE))
            fail (Error_Bad_File_Mode_Raw(path));
    }

    ReqFile(file)->path = path;

    Secure_Port(Canon(SYM_FILE), file, path /* , file->path */);

    // !!! For the moment, assume `path` has a lifetime that will exceed
    // the operation.  This will be easier to ensure once the REQ state is
    // Rebol-structured data, visible to the GC.
}

//
//  Cleanup_File: C
//
static void Cleanup_File(REBREQ *file)
{
    struct rebol_devreq *req = Req(file);
    req->flags &= ~RRF_OPEN;
}

//
//  Query_File_Or_Dir: C
//
// Produces a STD_FILE_INFO object.
//
void Query_File_Or_Dir(REBVAL *out, REBVAL *port, REBREQ *file)
{
    struct rebol_devreq *req = Req(file);

    REBVAL *info = rebValueQ(
        "copy ensure object! (", port , ")/scheme/info", rebEND
    ); // shallow copy

    REBCTX *ctx = VAL_CONTEXT(info);

    Init_Word(
        CTX_VAR(ctx, STD_FILE_INFO_TYPE),
        (req->modes & RFM_DIR) ? Canon(SYM_DIR) : Canon(SYM_FILE)
    );
    Init_Integer(CTX_VAR(ctx, STD_FILE_INFO_SIZE), ReqFile(file)->size);

    REBVAL *timestamp = File_Time_To_Rebol(file);
    Move_Value(CTX_VAR(ctx, STD_FILE_INFO_DATE), timestamp);
    rebRelease(timestamp);

    assert(IS_FILE(ReqFile(file)->path));
    Move_Value(CTX_VAR(ctx, STD_FILE_INFO_NAME), ReqFile(file)->path);

    Move_Value(out, info);
    rebRelease(info);
}

//
//  Open_File_Port: C
//
// Open a file port.
//
static void Open_File_Port(
    REBVAL *port,
    REBREQ *file,
    REBVAL *path
){
    UNUSED(port);

    struct rebol_devreq *req = Req(file);
    if (req->flags & RRF_OPEN)
        fail (Error_Already_Open_Raw(path));

    // Don't use OS_DO_DEVICE_SYNC() here, because we want to tack the file
    // name onto any error we get back.

    REBVAL *result = OS_DO_DEVICE(file, RDC_OPEN);
    assert(result != nullptr); // should be synchronous

    if (rebDid("error?", result, rebEND))
        fail (Error_Cannot_Open_Raw(ReqFile(file)->path, result));

    rebRelease(result);  // !!! ignore any other result?

    req->flags |= RRF_OPEN; // open it
}

REBINT Mode_Syms[] = {
    SYM_OWNER_READ,
    SYM_OWNER_WRITE,
    SYM_OWNER_EXECUTE,
    SYM_GROUP_READ,
    SYM_GROUP_WRITE,
    SYM_GROUP_EXECUTE,
    SYM_WORLD_READ,
    SYM_WORLD_WRITE,
    SYM_WORLD_EXECUTE,
    0
};

//
//  Read_File_Port: C
//
// Read from a file port.
//
static void Read_File_Port(
    REBVAL *out,
    REBVAL *port,
    REBREQ *file,
    REBVAL *path,
    REBFLGS flags,
    REBCNT len
) {
    assert(IS_FILE(path));

    UNUSED(path);
    UNUSED(flags);
    UNUSED(port);

    struct rebol_devreq *req = Req(file);

    REBSER *ser = Make_Binary(len); // read result buffer
    TERM_BIN_LEN(ser, len);
    Init_Binary(out, ser);

    // Do the read, check for errors:
    req->common.data = BIN_HEAD(ser);
    req->length = len;

    OS_DO_DEVICE_SYNC(file, RDC_READ);

    SET_SERIES_LEN(ser, req->actual);
    TERM_SEQUENCE(ser);
}

//
//  Write_File_Port: C
//
// !!! `len` comes from /PART, it should be in characters if a string and
// in bytes if a BINARY!.  It seems to disregard it if the data is BLOCK!
//
static void Write_File_Port(REBREQ *file, REBVAL *data, REBCNT len, bool lines)
{
    struct rebol_devreq *req = Req(file);

    if (IS_BLOCK(data)) {
        // Form the values of the block
        // !! Could be made more efficient if we broke the FORM
        // into 32K chunks for writing.
        DECLARE_MOLD (mo);
        Push_Mold(mo);
        if (lines)
            SET_MOLD_FLAG(mo, MOLD_FLAG_LINES);
        Form_Value(mo, data);
        Init_Text(data, Pop_Molded_String(mo)); // fall to next section
        len = VAL_LEN_HEAD(data);
    }

    if (IS_TEXT(data)) {
        REBSIZ offset = VAL_OFFSET_FOR_INDEX(data, VAL_INDEX(data));
        REBSIZ size = VAL_SIZE_LIMIT_AT(NULL, data, len);

        req->common.data = BIN_AT(VAL_SERIES(data), offset);
        req->length = size;
        req->modes |= RFM_TEXT; // do LF => CR LF, e.g. on Windows
    }
    else {
        req->common.data = VAL_BIN_AT(data);
        req->length = len;
        req->modes &= ~RFM_TEXT; // don't do LF => CR LF, e.g. on Windows
    }

    OS_DO_DEVICE_SYNC(file, RDC_WRITE);
}

//
//  Set_Length: C
//
// Note: converts 64bit number to 32bit. The requested size
// can never be greater than 4GB.  If limit isn't negative it
// constrains the size of the requested read.
//
static REBCNT Set_Length(REBREQ *file, REBI64 limit)
{
    // how much is already used
    REBI64 len = ReqFile(file)->size - ReqFile(file)->index;

    // Compute and bound bytes remaining:
    if (len < 0)
        return 0;
    len &= MAX_READ_MASK; // limit the size

    // Return requested length:
    if (limit < 0) return (REBCNT)len;

    // Limit size of requested read:
    if (limit > len) return cast(REBCNT, len);
    return cast(REBCNT, limit);
}

//
//  Set_Seek: C
//
// Computes the number of bytes that should be skipped.
//
static void Set_Seek(REBREQ *file, REBVAL *arg)
{
    struct rebol_devreq *req = Req(file);

    REBI64 cnt = Int64s(arg, 0);

    if (cnt > ReqFile(file)->size)
        cnt = ReqFile(file)->size;

    ReqFile(file)->index = cnt;

    req->modes |= RFM_RESEEK; // force a seek
}

//
//  File_Actor: C
//
// Internal port handler for files.
//
REB_R File_Actor(REBFRM *frame_, REBVAL *port, const REBVAL *verb)
{
    REBCTX *ctx = VAL_CONTEXT(port);
    REBVAL *spec = CTX_VAR(ctx, STD_PORT_SPEC);
    if (!IS_OBJECT(spec))
        fail (Error_Invalid_Spec_Raw(spec));

    REBVAL *path = Obj_Value(spec, STD_PORT_SPEC_HEAD_REF);
    if (path == NULL)
        fail (Error_Invalid_Spec_Raw(spec));

    if (IS_URL(path))
        path = Obj_Value(spec, STD_PORT_SPEC_HEAD_PATH);
    else if (!IS_FILE(path))
        fail (Error_Invalid_Spec_Raw(path));

    REBREQ *file = Ensure_Port_State(port, &Dev_File);
    struct rebol_devreq *req = Req(file);

    // !!! R3-Alpha never implemented quite a number of operations on files,
    // including FLUSH, POKE, etc.

    switch (VAL_WORD_SYM(verb)) {

    case SYM_REFLECT: {
        INCLUDE_PARAMS_OF_REFLECT;

        UNUSED(ARG(value)); // implicitly comes from `port`
        REBSYM property = VAL_WORD_SYM(ARG(property));
        assert(property != SYM_0);

        switch (property) {
        case SYM_INDEX:
            return Init_Integer(D_OUT, ReqFile(file)->index + 1);

        case SYM_LENGTH:
            //
            // Comment said "clip at zero"
            ///
            return Init_Integer(D_OUT, ReqFile(file)->size - ReqFile(file)->index);

        case SYM_HEAD:
            ReqFile(file)->index = 0;
            req->modes |= RFM_RESEEK;
            RETURN (port);

        case SYM_TAIL:
            ReqFile(file)->index = ReqFile(file)->size;
            req->modes |= RFM_RESEEK;
            RETURN (port);

        case SYM_HEAD_Q:
            return Init_Logic(D_OUT, ReqFile(file)->index == 0);

        case SYM_TAIL_Q:
            return Init_Logic(D_OUT, ReqFile(file)->index >= ReqFile(file)->size);

        case SYM_PAST_Q:
            return Init_Logic(D_OUT, ReqFile(file)->index > ReqFile(file)->size);

        case SYM_OPEN_Q:
            return Init_Logic(D_OUT, did (req->flags & RRF_OPEN));

        default:
            break;
        }

        break; }

    case SYM_READ: {
        INCLUDE_PARAMS_OF_READ;

        UNUSED(PAR(source));
        UNUSED(PAR(string)); // handled in dispatcher
        UNUSED(PAR(lines)); // handled in dispatcher

        REBFLGS flags = 0;

        // Handle the READ %file shortcut case, where the FILE! has been
        // converted into a PORT! but has not been opened yet.

        bool opened;
        if (req->flags & RRF_OPEN)
            opened = false; // was already open
        else {
            REBCNT nargs = AM_OPEN_READ;
            if (REF(seek))
                nargs |= AM_OPEN_SEEK;
            Setup_File(file, nargs, path);
            Open_File_Port(port, file, path);
            opened = true; // had to be opened (shortcut case)
        }

        if (REF(seek))
            Set_Seek(file, ARG(seek));

        REBCNT len = Set_Length(file, REF(part) ? VAL_INT64(ARG(part)) : -1);
        Read_File_Port(D_OUT, port, file, path, flags, len);

        if (opened) {
            REBVAL *result = OS_DO_DEVICE(file, RDC_CLOSE);
            assert(result != NULL); // should be synchronous

            Cleanup_File(file);

            if (rebDid("error?", result, rebEND))
                rebJumps("FAIL", result, rebEND);

            rebRelease(result); // ignore result
        }

        return D_OUT; }

    case SYM_APPEND:
        //
        // !!! This is hacky, but less hacky than falling through to SYM_WRITE
        // assuming the frame is the same for APPEND and WRITE (which is what
        // R3-Alpha did).  Review.
        //
        return Retrigger_Append_As_Write(frame_);

    case SYM_WRITE: {
        INCLUDE_PARAMS_OF_WRITE;

        UNUSED(PAR(destination));

        if (REF(allow))
            fail (Error_Bad_Refines_Raw());

        REBVAL *data = ARG(data); // binary, string, or block

        // Handle the WRITE %file shortcut case, where the FILE! is converted
        // to a PORT! but it hasn't been opened yet.

        bool opened;
        if (req->flags & RRF_OPEN) {
            if (not (req->modes & RFM_WRITE))
                fail (Error_Read_Only_Raw(path));

            opened = false; // already open
        }
        else {
            REBCNT nargs = AM_OPEN_WRITE;
            if (REF(seek) || REF(append))
                nargs |= AM_OPEN_SEEK;
            else
                nargs |= AM_OPEN_NEW;
            Setup_File(file, nargs, path);
            Open_File_Port(port, file, path);
            opened = true;
        }

        if (REF(append)) {
            ReqFile(file)->index = -1; // append
            req->modes |= RFM_RESEEK;
        }
        if (REF(seek))
            Set_Seek(file, ARG(seek));

        // Determine length. Clip /PART to size of string if needed.
        REBCNT len = VAL_LEN_AT(data);
        if (REF(part)) {
            REBCNT n = Int32s(ARG(part), 0);
            if (n <= len)
                len = n;
        }

        Write_File_Port(file, data, len, REF(lines));

        if (opened) {
            REBVAL *result = OS_DO_DEVICE(file, RDC_CLOSE);
            assert(result != NULL); // should be synchronous

            Cleanup_File(file);

            if (rebDid("error?", result, rebEND))
                rebJumps("FAIL", result, rebEND);

            rebRelease(result);
        }

        RETURN (port); }

    case SYM_OPEN: {
        INCLUDE_PARAMS_OF_OPEN;

        UNUSED(PAR(spec));

        if (REF(allow))
            fail (Error_Bad_Refines_Raw());

        REBFLGS flags = (
            (REF(new) ? AM_OPEN_NEW : 0)
            | (REF(read) or not REF(write) ? AM_OPEN_READ : 0)
            | (REF(write) or not REF(read) ? AM_OPEN_WRITE : 0)
            | (REF(seek) ? AM_OPEN_SEEK : 0)
            | (REF(allow) ? AM_OPEN_ALLOW : 0)
        );
        Setup_File(file, flags, path);

        // !!! need to change file modes to R/O if necessary

        Open_File_Port(port, file, path);

        RETURN (port); }

    case SYM_COPY: {
        INCLUDE_PARAMS_OF_COPY;

        UNUSED(PAR(value));

        if (REF(deep) or REF(types))
            fail (Error_Bad_Refines_Raw());

        if (not (req->flags & RRF_OPEN))
            fail (Error_Not_Open_Raw(path)); // !!! wrong msg

        REBCNT len = Set_Length(file, REF(part) ? VAL_INT64(ARG(part)) : -1);
        REBFLGS flags = 0;
        Read_File_Port(D_OUT, port, file, path, flags, len);
        return D_OUT; }

    case SYM_CLOSE: {
        INCLUDE_PARAMS_OF_CLOSE;
        UNUSED(PAR(port));

        if (req->flags & RRF_OPEN) {
            REBVAL *result = OS_DO_DEVICE(file, RDC_CLOSE);
            assert(result != NULL); // should be synchronous

            Cleanup_File(file);

            if (rebDid("error?", result, rebEND))
                rebJumps("FAIL", result, rebEND);

            rebRelease(result); // ignore error
        }
        RETURN (port); }

    case SYM_DELETE: {
        INCLUDE_PARAMS_OF_DELETE;
        UNUSED(PAR(port));

        if (req->flags & RRF_OPEN)
            fail (Error_No_Delete_Raw(path));
        Setup_File(file, 0, path);

        REBVAL *result = OS_DO_DEVICE(file, RDC_DELETE);
        assert(result != NULL); // should be synchronous

        if (rebDid("error?", result, rebEND))
            rebJumps("FAIL", result, rebEND);

        rebRelease(result); // ignore result
        RETURN (port); }

    case SYM_RENAME: {
        INCLUDE_PARAMS_OF_RENAME;

        if (req->flags & RRF_OPEN)
            fail (Error_No_Rename_Raw(path));

        Setup_File(file, 0, path);

        req->common.data = cast(REBYTE*, ARG(to)); // !!! hack!

        REBVAL *result = OS_DO_DEVICE(file, RDC_RENAME);
        assert(result != NULL); // should be synchronous
        if (rebDid("error?", result, rebEND))
            rebJumps("FAIL", result, rebEND);
        rebRelease(result); // ignore result

        RETURN (ARG(from)); }

    case SYM_CREATE: {
        if (not (req->flags & RRF_OPEN)) {
            Setup_File(file, AM_OPEN_WRITE | AM_OPEN_NEW, path);

            REBVAL *cr_result = OS_DO_DEVICE(file, RDC_CREATE);
            assert(cr_result != NULL);
            if (rebDid("error?", cr_result, rebEND))
                rebJumps("FAIL", cr_result, rebEND);
            rebRelease(cr_result);

            REBVAL *cl_result = OS_DO_DEVICE(file, RDC_CLOSE);
            assert(cl_result != NULL);
            if (rebDid("error?", cl_result, rebEND))
                rebJumps("FAIL", cl_result, rebEND);
            rebRelease(cl_result);
        }

        // !!! should it leave file open???

        RETURN (port); }

    case SYM_QUERY: {
        INCLUDE_PARAMS_OF_QUERY;

        UNUSED(PAR(target));

        if (REF(mode))
            fail (Error_Bad_Refines_Raw());

        if (not (req->flags & RRF_OPEN)) {
            Setup_File(file, 0, path);
            REBVAL *result = OS_DO_DEVICE(file, RDC_QUERY);
            assert(result != NULL);
            if (rebDid("error?", result, rebEND)) {
                rebRelease(result); // !!! R3-Alpha returned blank on error
                return nullptr;
            }
            rebRelease(result); // ignore result
        }
        Query_File_Or_Dir(D_OUT, port, file);

        // !!! free file path?

        return D_OUT; }

    case SYM_MODIFY: {
        INCLUDE_PARAMS_OF_MODIFY;

        UNUSED(PAR(target));
        UNUSED(PAR(field));
        UNUSED(PAR(value));

        // !!! Set_Mode_Value() was called here, but a no-op in R3-Alpha
        if (not (req->flags & RRF_OPEN)) {
            Setup_File(file, 0, path);

            REBVAL *result = OS_DO_DEVICE(file, RDC_MODIFY);
            assert(result != NULL);
            if (rebDid("error?", result, rebEND)) {
                rebRelease(result); // !!! R3-Alpha returned blank on error
                return Init_False(D_OUT);
            }
            rebRelease(result); // ignore result
        }
        return Init_True(D_OUT); }

    case SYM_SKIP: {
        INCLUDE_PARAMS_OF_SKIP;

        UNUSED(PAR(series));
        UNUSED(REF(only)); // !!! Should /ONLY behave differently?

        ReqFile(file)->index += Get_Num_From_Arg(ARG(offset));
        req->modes |= RFM_RESEEK;
        RETURN (port); }

    case SYM_CLEAR: {
        // !! check for write enabled?
        req->modes |= RFM_RESEEK;
        req->modes |= RFM_TRUNCATE;
        req->length = 0;

        OS_DO_DEVICE_SYNC(file, RDC_WRITE);
        RETURN (port); }

    default:
        break;
    }

    return R_UNHANDLED;
}


text:
{% load labeled_status %}

{% if status %}
    {% if status == 'NEW' %}
        {{ status|human }}
    {% elif status == 'ACTIVE' %}
        {{ status|human }}
    {% elif status == 'FINISHED' %}
        {{ status|human }}
    {% elif status == 'SUSPENDED' %}
        {{ status|human }}
    {% elif status == 'CLOSED' %}
        {{ status|human }}
    {% else %}
        {{ status|human }}
    {% endif %}
{% endif %}


text:
package com.subgraph.orchid.circuits.hs;

import com.subgraph.orchid.crypto.TorPublicKey;
import com.subgraph.orchid.data.HexDigest;
import com.subgraph.orchid.data.IPv4Address;

public class IntroductionPoint {

	private HexDigest identity;
	private IPv4Address address;
	private int onionPort;
	private TorPublicKey onionKey;
	private TorPublicKey serviceKey;

	IntroductionPoint(HexDigest identity) {
		this.identity = identity;
	}

	void setAddress(IPv4Address address) {
		this.address = address;
	}

	void setOnionPort(int onionPort) {
		this.onionPort = onionPort;
	}

	void setOnionKey(TorPublicKey onionKey) {
		this.onionKey = onionKey;
	}

	void setServiceKey(TorPublicKey serviceKey) {
		this.serviceKey = serviceKey;
	}

	boolean isValidDocument() {
		return identity != null && address != null && onionPort != 0 && onionKey != null && serviceKey != null;
	}

	public HexDigest getIdentity() {
		return identity;
	}

	public IPv4Address getAddress() {
		return address;
	}

	public int getPort() {
		return onionPort;
	}

	public TorPublicKey getOnionKey() {
		return onionKey;
	}

	public TorPublicKey getServiceKey() {
		return serviceKey;
	}
}


text:
require 'http-client'
require 'json'

class PostcodeLookup
  def initialize(postcode)
    @postcode = postcode
  end

  def lookup
    uri = URI.encode("http://api.postcodes.io/postcodes/#{@postcode}")
    response = HTTP::Client.get(uri)
    json_response = JSON.parse(response.body)

    return {} unless response.code == 200

    json_response['result']
  end
end


text:
/*
 * In order for modal windows to use our custom theme, we have to define them in tiapp.xml, like:
 *             	<activity android:configChanges="keyboardHidden|orientation|screenSize"
            		android:name="org.appcelerator.titanium.TiModalActivity" />

    For more info, see: http://docs.appcelerator.com/titanium/latest/#!/guide/Android_Themes

    1/8/14
    NOTE: Starting in Ti 3.2.0, TiModalActivity is no longer being used, however, TiTranslucentActivity is, and
    it has a default theme applied to it (and modal windows), so the the above tiapp.xml entry needs to be changed to:

    <activity android:configChanges="keyboardHidden|orientation|screenSize"
            		android:name="org.appcelerator.titanium.TiTranslucentActivity" />

 */


text:
object Test extends dotty.runtime.LegacyApp {
  implicit def anyList[T]: List[T] = Nil

  implicit def intList: List[Int] = 42::24::Nil

  def foo[T](implicit x: T) = x

  val s = foo[List[Int]]

  println(s)  // correct - prints "List(42, 24)"

  implicit def tupleList[T](implicit t: List[T]): List[(T,T)] = t.map(x => (x,x))

  val t = foo[List[Tuple2[Int,Int]]]

  println(t)  // incorrect - prints "List()"
}


text:
module VmHelper
  include RequestInfoHelper

  include_concern 'TextualSummary'
  include_concern 'ComplianceSummaryHelper'

  # TODO: These methods can be removed once the Summary and ListNav data layer is consolidated.
  def last_date(request_type)
    @last_date ||= {}
    return @last_date[request_type] if @last_date.key?(request_type)
    @last_date[request_type] = send("last_date_#{request_type}")
  end

  def last_date_processes
    @record.operating_system&.processes&.maximum(:updated_on)
  end

  def set_controller_action
    url = request.parameters[:controller]
    action = "x_show"
    return url, action
  end

  def textual_cloud_network
    return nil unless @record.kind_of?(ManageIQ::Providers::CloudManager::Vm)
    {:label => _("Virtual Private Cloud"), :value => @record.cloud_network ? @record.cloud_network.name : _('None')}
  end

  def textual_cloud_subnet
    return nil unless @record.kind_of?(ManageIQ::Providers::CloudManager::Vm)
    {:label => _("Cloud Subnet"), :value => @record.cloud_subnet ? @record.cloud_subnet.name : _('None')}
  end

  def calculate_disk_size(size)
    size.blank? ? nil : number_to_human_size(size, :precision => 2)
  end

  def calculate_disk_name(disk)
    case disk.device_type
    when "cdrom-raw"
      "CD-ROM (IDE #{disk.location})"
    when "atapi-cdrom"
      "ATAPI CD-ROM (IDE #{disk.location})"
    when "cdrom-image"
      "CD-ROM Image (IDE #{disk.location})"
    when "disk"
      if disk.controller_type.start_with?("ide")
        "Hard Disk (IDE #{disk.location})"
      elsif disk.controller_type.start_with?("scsi")
        "Hard Disk (SCSI #{disk.location})"
      else
        "#{disk.controller_type} #{disk.location}"
      end
    when "ide"
      "Hard Disk (IDE #{disk.location})"
    when "scsi", "scsi-hardDisk"
      "Hard Disk (SCSI #{disk.location})"
    when "scsi-passthru"
      "Generic SCSI (#{disk.location})"
    when "floppy"
      "Floppy Drive (SIO #{disk.location})"
    else
      "#{disk.controller_type} #{disk.location}"
    end
  end
end


text:
var repository = require('./mathRepository');
module.exports = {
    /**
     * Factorial Function
     * @param   {Number} factNo input number
     * @returns {Number} the factorial
     */
    getFactorail: function(factNo) {
        if ((!isNaN(factNo)) || (factNo < 0)) {
            return undefined;
        } else {
            retun(repository.factorial(factNo));
        }
    }
}

console.log(repository.matrixMultiply(2,3));
//console.log(repository.factorial(5));


text:
Packages the local artifacts (local paths) that your AWS CloudFormation template
references. The command uploads local artifacts, such as source code for an AWS
Lambda function or a Swagger file for an AWS API Gateway REST API, to an S3
bucket. The command returns a copy of your template, replacing references to
local artifacts with the S3 location where the command uploaded the artifacts.

Use this command to quickly upload local artifacts that might be required by
your template. After you package your template's artifacts, run the deploy
command to ``deploy`` the returned template.

This command can upload local artifacts specified by following properties of a resource:

    - ``BodyS3Location`` property for the ``AWS::ApiGateway::RestApi`` resource
    - ``Code`` property for the ``AWS::Lambda::Function`` resource
    - ``CodeUri`` property for the ``AWS::Serverless::Function`` resource
    - ``DefinitionUri`` property for the ``AWS::Serverless::Api`` resource
    - ``SourceBundle`` property for the ``AWS::ElasticBeanstalk::ApplicationVersion`` resource
    - ``TemplateURL`` property for the ``AWS::CloudFormation::Stack`` resource

To specify a local artifact in your template, specify a path to a local file or folder,
as either an absolute or relative path. The relative path is a location
that is relative to your template's location.

For example, if your AWS Lambda function source code is in the
``/home/user/code/lambdafunction/`` folder, specify
`` CodeUri: /home/user/code/lambdafunction`` for the
``AWS::Serverless::Function`` resource. The command returns a template and replaces
the local path with the S3 location: ``CodeUri: s3://mybucket/lambdafunction.zip``.

If you specify a file, the command directly uploads it to the S3 bucket. If you
specify a folder, the command zips the folder and then uploads the .zip file.
For most resources, if you don't specify a path, the command zips and uploads the
current working directory. The exception is ``AWS::ApiGateway::RestApi``;
if you don't specify a ``BodyS3Location``, this command will not upload an artifact to S3.

Before the command uploads artifacts, it checks if the artifacts are already
present in the S3 bucket to prevent unnecessary uploads. The command uses MD5
checksums to compare files. If the values match, the command doesn't upload the
artifacts. Use the ``--force flag`` to skip this check and always upload the
artifacts.


text:
use std::{
    cell::{Ref, RefCell, RefMut},
    mem::size_of,
    num::NonZeroU64,
};

use crate::{
    client::render::{
        ui::{
            layout::{Layout, Size},
            screen_space_vertex_transform,
        },
        uniform::{self, DynamicUniformBuffer, DynamicUniformBufferBlock},
        Extent2d, GraphicsState, Pipeline, TextureData, DIFFUSE_ATTACHMENT_FORMAT,
    },
    common::{util::any_slice_as_bytes, wad::QPic},
};

use cgmath::Matrix4;

pub const VERTICES: [QuadVertex; 6] = [
    QuadVertex {
        position: [0.0, 0.0],
        texcoord: [0.0, 1.0],
    },
    QuadVertex {
        position: [0.0, 1.0],
        texcoord: [0.0, 0.0],
    },
    QuadVertex {
        position: [1.0, 1.0],
        texcoord: [1.0, 0.0],
    },
    QuadVertex {
        position: [0.0, 0.0],
        texcoord: [0.0, 1.0],
    },
    QuadVertex {
        position: [1.0, 1.0],
        texcoord: [1.0, 0.0],
    },
    QuadVertex {
        position: [1.0, 0.0],
        texcoord: [1.0, 1.0],
    },
];

// these type aliases are here to aid readability of e.g. size_of::<Position>()
pub type Position = [f32; 2];
pub type Texcoord = [f32; 2];

#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct QuadVertex {
    position: Position,
    texcoord: Texcoord,
}

lazy_static! {
    static ref VERTEX_BUFFER_ATTRIBUTES: Vec<wgpu::VertexAttribute> = vec![
        // position
        wgpu::VertexAttribute {
            offset: 0,
            format: wgpu::VertexFormat::Float32x2,
            shader_location: 0,
        },
        // diffuse texcoord
        wgpu::VertexAttribute {
            offset: size_of::<Position>() as u64,
            format: wgpu::VertexFormat::Float32x2,
            shader_location: 1,
        },
    ];
}

pub struct QuadPipeline {
    pipeline: wgpu::RenderPipeline,
    bind_group_layouts: Vec<wgpu::BindGroupLayout>,
    vertex_buffer: wgpu::Buffer,
    uniform_buffer: RefCell<DynamicUniformBuffer<QuadUniforms>>,
    uniform_buffer_blocks: RefCell<Vec<DynamicUniformBufferBlock<QuadUniforms>>>,
}

impl QuadPipeline {
    pub fn new(
        device: &wgpu::Device,
        compiler: &mut shaderc::Compiler,
        sample_count: u32,
    ) -> QuadPipeline {
        let (pipeline, bind_group_layouts) =
            QuadPipeline::create(device, compiler, &[], sample_count);

        use wgpu::util::DeviceExt as _;
        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: None,
            contents: unsafe { any_slice_as_bytes(&VERTICES) },
            usage: wgpu::BufferUsage::VERTEX,
        });

        let uniform_buffer = RefCell::new(DynamicUniformBuffer::new(device));
        let uniform_buffer_blocks = RefCell::new(Vec::new());

        QuadPipeline {
            pipeline,
            bind_group_layouts,
            vertex_buffer,
            uniform_buffer,
            uniform_buffer_blocks,
        }
    }

    pub fn rebuild(
        &mut self,
        device: &wgpu::Device,
        compiler: &mut shaderc::Compiler,
        sample_count: u32,
    ) {
        let layout_refs = self.bind_group_layouts.iter().collect::<Vec<_>>();
        self.pipeline = QuadPipeline::recreate(device, compiler, &layout_refs, sample_count);
    }

    pub fn pipeline(&self) -> &wgpu::RenderPipeline {
        &self.pipeline
    }

    pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] {
        &self.bind_group_layouts
    }

    pub fn vertex_buffer(&self) -> &wgpu::Buffer {
        &self.vertex_buffer
    }

    pub fn uniform_buffer(&self) -> Ref<DynamicUniformBuffer<QuadUniforms>> {
        self.uniform_buffer.borrow()
    }

    pub fn uniform_buffer_mut(&self) -> RefMut<DynamicUniformBuffer<QuadUniforms>> {
        self.uniform_buffer.borrow_mut()
    }

    pub fn uniform_buffer_blocks(&self) -> Ref<Vec<DynamicUniformBufferBlock<QuadUniforms>>> {
        self.uniform_buffer_blocks.borrow()
    }

    pub fn uniform_buffer_blocks_mut(
        &self,
    ) -> RefMut<Vec<DynamicUniformBufferBlock<QuadUniforms>>> {
        self.uniform_buffer_blocks.borrow_mut()
    }
}

const BIND_GROUP_LAYOUT_ENTRIES: &[&[wgpu::BindGroupLayoutEntry]] = &[
    &[
        // sampler
        wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStage::FRAGMENT,
            ty: wgpu::BindingType::Sampler {
                filtering: true,
                comparison: false,
            },
            count: None,
        },
    ],
    &[
        // texture
        wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStage::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                view_dimension: wgpu::TextureViewDimension::D2,
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                multisampled: false,
            },
            count: None,
        },
    ],
    &[
        // transform matrix
        // TODO: move to push constants once they're exposed in wgpu
        wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStage::all(),
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: true,
                min_binding_size: NonZeroU64::new(size_of::<QuadUniforms>() as u64),
            },
            count: None,
        },
    ],
];

impl Pipeline for QuadPipeline {
    type VertexPushConstants = ();
    type SharedPushConstants = ();
    type FragmentPushConstants = ();

    fn name() -> &'static str {
        "quad"
    }

    fn bind_group_layout_descriptors() -> Vec<wgpu::BindGroupLayoutDescriptor<'static>> {
        vec![
            // group 0: per-frame
            wgpu::BindGroupLayoutDescriptor {
                label: Some("per-frame quad bind group"),
                entries: BIND_GROUP_LAYOUT_ENTRIES[0],
            },
            // group 1: per-texture
            wgpu::BindGroupLayoutDescriptor {
                label: Some("per-texture quad bind group"),
                entries: BIND_GROUP_LAYOUT_ENTRIES[1],
            },
            // group 2: per-quad
            wgpu::BindGroupLayoutDescriptor {
                label: Some("per-texture quad bind group"),
                entries: BIND_GROUP_LAYOUT_ENTRIES[2],
            },
        ]
    }

    fn vertex_shader() -> &'static str {
        include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shaders/quad.vert"))
    }

    fn fragment_shader() -> &'static str {
        include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shaders/quad.frag"))
    }

    fn primitive_state() -> wgpu::PrimitiveState {
        wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Cw,
            cull_mode: Some(wgpu::Face::Back),
            clamp_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        }
    }

    fn color_target_states() -> Vec<wgpu::ColorTargetState> {
        vec![wgpu::ColorTargetState {
            format: DIFFUSE_ATTACHMENT_FORMAT,
            blend: Some(wgpu::BlendState::REPLACE),
            write_mask: wgpu::ColorWrite::ALL,
        }]
    }

    fn depth_stencil_state() -> Option<wgpu::DepthStencilState> {
        None
    }

    // NOTE: if the vertex format is changed, this descriptor must also be changed accordingly.
    fn vertex_buffer_layouts() -> Vec<wgpu::VertexBufferLayout<'static>> {
        vec![wgpu::VertexBufferLayout {
            array_stride: size_of::<QuadVertex>() as u64,
            step_mode: wgpu::InputStepMode::Vertex,
            attributes: &VERTEX_BUFFER_ATTRIBUTES[..],
        }]
    }
}

#[repr(C, align(256))]
#[derive(Clone, Copy, Debug)]
pub struct QuadUniforms {
    transform: Matrix4<f32>,
}

pub struct QuadTexture {
    #[allow(dead_code)]
    texture: wgpu::Texture,
    #[allow(dead_code)]
    texture_view: wgpu::TextureView,
    bind_group: wgpu::BindGroup,
    width: u32,
    height: u32,
}

impl QuadTexture {
    pub fn from_qpic(state: &GraphicsState, qpic: &QPic) -> QuadTexture {
        let (diffuse_data, _) = state.palette().translate(qpic.indices());
        let texture = state.create_texture(
            None,
            qpic.width(),
            qpic.height(),
            &TextureData::Diffuse(diffuse_data),
        );
        let texture_view = texture.create_view(&Default::default());
        let bind_group = state
            .device()
            .create_bind_group(&wgpu::BindGroupDescriptor {
                label: None,
                layout: &state.quad_pipeline().bind_group_layouts()[1],
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&texture_view),
                }],
            });

        QuadTexture {
            texture,
            texture_view,
            bind_group,
            width: qpic.width(),
            height: qpic.height(),
        }
    }

    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    pub fn scale_width(&self, scale: f32) -> u32 {
        (self.width as f32 * scale) as u32
    }

    pub fn scale_height(&self, scale: f32) -> u32 {
        (self.height as f32 * scale) as u32
    }
}

/// A command which specifies how a quad should be rendered.
pub struct QuadRendererCommand<'a> {
    /// The texture to be mapped to the quad.
    pub texture: &'a QuadTexture,

    /// The layout specifying the size and position of the quad on the screen.
    pub layout: Layout,
}

pub struct QuadRenderer {
    sampler_bind_group: wgpu::BindGroup,
    transform_bind_group: wgpu::BindGroup,
}

impl QuadRenderer {
    pub fn new(state: &GraphicsState) -> QuadRenderer {
        let sampler_bind_group = state
            .device()
            .create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("quad sampler bind group"),
                layout: &state.quad_pipeline().bind_group_layouts()[0],
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Sampler(state.diffuse_sampler()),
                }],
            });
        let transform_bind_group = state
            .device()
            .create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("quad transform bind group"),
                layout: &state.quad_pipeline().bind_group_layouts()[2],
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: state.quad_pipeline().uniform_buffer().buffer(),
                        offset: 0,
                        size: Some(NonZeroU64::new(size_of::<QuadUniforms>() as u64).unwrap()),
                    }),
                }],
            });

        QuadRenderer {
            sampler_bind_group,
            transform_bind_group,
        }
    }

    fn generate_uniforms<'cmds>(
        &self,
        commands: &[QuadRendererCommand<'cmds>],
        target_size: Extent2d,
    ) -> Vec<QuadUniforms> {
        let mut uniforms = Vec::new();

        for cmd in commands {
            let QuadRendererCommand {
                texture,
                layout:
                    Layout {
                        position,
                        anchor,
                        size,
                    },
            } = *cmd;

            let scale = match size {
                Size::Scale { factor } => factor,
                _ => 1.0,
            };

            let Extent2d {
                width: display_width,
                height: display_height,
            } = target_size;

            let (screen_x, screen_y) = position.to_xy(display_width, display_height, scale);
            let (quad_x, quad_y) = anchor.to_xy(texture.width, texture.height);
            let x = screen_x - (quad_x as f32 * scale) as i32;
            let y = screen_y - (quad_y as f32 * scale) as i32;
            let (quad_width, quad_height) =
                size.to_wh(texture.width, texture.height, display_width, display_height);

            uniforms.push(QuadUniforms {
                transform: screen_space_vertex_transform(
                    display_width,
                    display_height,
                    quad_width,
                    quad_height,
                    x,
                    y,
                ),
            });
        }

        uniforms
    }

    pub fn record_draw<'pass, 'cmds>(
        &'pass self,
        state: &'pass GraphicsState,
        pass: &mut wgpu::RenderPass<'pass>,
        target_size: Extent2d,
        commands: &'pass [QuadRendererCommand<'pass>],
    ) {
        // update uniform buffer
        let uniforms = self.generate_uniforms(commands, target_size);
        uniform::clear_and_rewrite(
            state.queue(),
            &mut state.quad_pipeline().uniform_buffer_mut(),
            &mut state.quad_pipeline().uniform_buffer_blocks_mut(),
            &uniforms,
        );

        pass.set_pipeline(state.quad_pipeline().pipeline());
        pass.set_vertex_buffer(0, state.quad_pipeline().vertex_buffer().slice(..));
        pass.set_bind_group(0, &self.sampler_bind_group, &[]);
        for (cmd, block) in commands
            .iter()
            .zip(state.quad_pipeline().uniform_buffer_blocks().iter())
        {
            pass.set_bind_group(1, &cmd.texture.bind_group, &[]);
            pass.set_bind_group(2, &self.transform_bind_group, &[block.offset()]);
            pass.draw(0..6, 0..1);
        }
    }
}


text:
<?php get_header(); ?>

        <?php

            /**
             *
             * @hooked SingleCongregationController@display_banner - 10
             */

            do_action( 'display_banner' );

        ?>

            <?php

                /**
                 *
                 * @hooked AppController@display_badges - 10
                 */

                do_action( 'display_badges' );

            ?>

            <?php

                /**
                 *
                 * @hooked SingleCongregationController@display_instagram - 10
                 */

                do_action( 'display_instagram' );

            ?>

Hello!

Hi! I'm Sophie, the Congregational Pastor of Est. 1825 Guildford, the students and young adults congregation of Family Church in Guildford. I grew up near Guildford and after time away at University in Exeter and further study in London, I returned in early 2010 and have been living in and around Guildford and part of Family Church ever since.

It was during my time at University and the start of my professional life that I really got to know God and got excited about faith, and my own crazy journey through working in the City to now working as a Chaplain in Further Education ignited a desire to help students and young adults to discover all God is and to build an unshakeable faith on His word and truth. I'm passionate about seeing this next generation of world changers rise up as a voice above the noise in our culture, in shunning what the world offers and shouting a message of relentless hope and sacrificial love to those around them; jumping head first into the fun and crazy adventure of following God!

Our young adults community is a core part of the Family Church Guildford congregation which meets every Sunday morning - here we get to serve as part of amazing diverse teams with people of all ages, married couples and families, who love getting to know the young adults and welcoming them into their homes.

We then meet for our own dedicated young adults service every Sunday evening at the Empower Centre Guildford where we have a time of praise and worship, are open to the Holy Spirit and hear some practical bible-based teaching on issues that are relevant to all the joys and battles you face as a student or young professional! We really want you to feel part of our young adults community so this is always a great time to hang out and get to know the other 18-25 year olds better, and hear about all the social events, connect groups and discipleship opportunities that we run specifically for young adults during the week.

So if you're between 18 and 25, whatever your background or church experience - whether you're new to the area, looking for a refreshing church experience, or simply inquisitive about the whole 'God thing', come pay us a visit soon in the morning or evening – our amazing team of young adults leaders would love to meet you and help you to get stuck in and grow in your faith.

 Read more

        <?php

             /**
             *
             * @hooked SingleCongregationController@display_location - 10
             */

            do_action( 'display_location' );

        ?>

                    View more events

Empower Centre Guildford

21-22 Woodbridge Meadows

Guildford GU1 1BA

01483 455 244

info@family-church.org.uk

<?php get_footer(); ?>


text:
package retry

import (
	"crypto/sha1"
	"fmt"
	"github.com/everalbum/go-resque"
	"github.com/everalbum/goworker"
	"github.com/garyburd/redigo/redis"
	"github.com/pkg/errors"
	"strings"
	"time"
)

type backoff struct {
	jobName         string
	worker          func(string, ...interface{}) error
	RetryLimit      int
	BackoffStrategy []int
	SaveFailedJob   bool
}

func NewBackoff(jobName string, workerFunc func(string, ...interface{}) error) *backoff {
	eb := new(backoff)
	eb.jobName = jobName
	eb.worker = workerFunc

	// Default backoff strategy in seconds
	eb.BackoffStrategy = []int{0, 60, 600, 3600, 10800, 21600} // 0s, 1m, 10m, 1h, 3h, 6h
	eb.RetryLimit = len(eb.BackoffStrategy)
	return eb
}

func (eb backoff) WorkerFunc() func(string, ...interface{}) error {
	return func(queue string, args ...interface{}) error {
		retryKey := eb.retryKey(args)

		// Setup the attempt
		retryAttempt, err := eb.beginAttempt(retryKey)
		if err != nil {
			return err
		}

		// Run the job
		workerErr := eb.worker(queue, args...)

		// Get redis connection
		conn, err := goworker.GetConn()
		if err != nil {
			return err
		}
		defer goworker.PutConn(conn)

		// Success, just clear the retry key
		if workerErr == nil {
			conn.Do("DEL", retryKey)
			return nil
		}

		if retryAttempt >= eb.RetryLimit {
			// If we've retried too many times, give up
			conn.Do("DEL", retryKey)
			if eb.SaveFailedJob {
				_, err = resque.Failure(conn.Conn, queue, eb.jobName, args...)
				if err != nil {
					return err
				}
			}
			// Wrap an error in order to expose underlying stack traces
			return errors.Wrap(workerErr, "Final attempt failed")
		} else {
			// Otherwise schedule the retry attempt
			seconds := eb.retryDelay(retryAttempt)
			if seconds <= 0 {
				// If there's no delay, just enqueue it
				_, err = resque.Enqueue(conn.Conn, queue, eb.jobName, args...)
			} else {
				// Otherwise schedule it
				delay := time.Duration(seconds) * time.Second
				err = resque.EnqueueIn(conn.Conn, delay, queue, eb.jobName, args...)
			}

			if err != nil {
				return err
			}
		}

		// Create new error in order to ignore underlying stack traces
		return errors.Errorf("retry: attempt %d of %d failed: %v", retryAttempt, eb.RetryLimit, workerErr)
	}
}

func (eb backoff) beginAttempt(retryKey string) (int, error) {
	conn, err := goworker.GetConn()
	if err != nil {
		return -1, err
	}
	defer goworker.PutConn(conn)

	// Create the retry key if not exists
	_, err = conn.Do("SETNX", retryKey, -1)
	if err != nil {
		return -1, err
	}

	// Increment the attempt we're on
	retryAttempt, err := redis.Int(conn.Do("INCR", retryKey))
	if err != nil {
		return -1, err
	}

	// Expire the retry key so we don't leave it hanging
	// (a week after it was supposed to be removed)
	conn.Do("EXPIRE", retryKey, eb.retryDelay(retryAttempt)+3600*24*7)

	return retryAttempt, nil
}

func (eb backoff) retryDelay(attempt int) int {
	if attempt > (len(eb.BackoffStrategy) - 1) {
		attempt = len(eb.BackoffStrategy) - 1
	}
	return eb.BackoffStrategy[attempt]
}

func (eb backoff) retryKey(args []interface{}) string {
	parts := []string{"resque", "resque-retry", eb.jobName, eb.retryIdentifier(args)}
	return strings.Join(parts, ":")
}

func (eb backoff) retryIdentifier(args []interface{}) string {
	params := make([]string, len(args))
	for i, value := range args {
		params[i] = fmt.Sprintf("%v", value)
	}

	h := sha1.New()
	h.Write([]byte(strings.Join(params, "-")))
	bs := h.Sum(nil)

	hash := fmt.Sprintf("%x", bs)

	return strings.Replace(hash, " ", "", -1)
}