text:
package org.apache.commons.math4.legacy.ode.nonstiff;

import org.apache.commons.math4.legacy.core.Field;
import org.apache.commons.math4.legacy.core.RealFieldElement;
import org.apache.commons.math4.legacy.ode.FieldEquationsMapper;
import org.apache.commons.math4.legacy.ode.FieldODEStateAndDerivative;
import org.apache.commons.math4.legacy.core.MathArrays;

/**
 * This class implements a simple Euler integrator for Ordinary
 * Differential Equations.
 *
 *
The Euler algorithm is the simplest one that can be used to
 * integrate ordinary differential equations. It is a simple inversion
 * of the forward difference expression :
 * f'=(f(t+h)-f(t))/h which leads to
 * f(t+h)=f(t)+hf'. The interpolation scheme used for
 * dense output is the linear scheme already used for integration.

 *
 *
This algorithm looks cheap because it needs only one function
 * evaluation per step. However, as it uses linear estimates, it needs
 * very small steps to achieve high accuracy, and small steps lead to
 * numerical errors and instabilities.

 *
 *
This algorithm is almost never used and has been included in
 * this package only as a comparison reference for more useful
 * integrators.

 *
 * @see MidpointFieldIntegrator
 * @see ClassicalRungeKuttaFieldIntegrator
 * @see GillFieldIntegrator
 * @see ThreeEighthesFieldIntegrator
 * @see LutherFieldIntegrator
 * @param <T> the type of the field elements
 * @since 3.6
 */

public class EulerFieldIntegrator<T extends RealFieldElement<T>> extends RungeKuttaFieldIntegrator<T> {

    /** Simple constructor.
     * Build an Euler integrator with the given step.
     * @param field field to which the time and state vector elements belong
     * @param step integration step
     */
    public EulerFieldIntegrator(final Field<T> field, final T step) {
        super(field, "Euler", step);
    }

    /** {@inheritDoc} */
    @Override
    public T[] getC() {
        return MathArrays.buildArray(getField(), 0);
    }

    /** {@inheritDoc} */
    @Override
    public T[][] getA() {
        return MathArrays.buildArray(getField(), 0, 0);
    }

    /** {@inheritDoc} */
    @Override
    public T[] getB() {
        final T[] b = MathArrays.buildArray(getField(), 1);
        b[0] = getField().getOne();
        return b;
    }

    /** {@inheritDoc} */
    @Override
    protected EulerFieldStepInterpolator<T>
        createInterpolator(final boolean forward, T[][] yDotK,
                           final FieldODEStateAndDerivative<T> globalPreviousState,
                           final FieldODEStateAndDerivative<T> globalCurrentState,
                           final FieldEquationsMapper<T> mapper) {
        return new EulerFieldStepInterpolator<>(getField(), forward, yDotK,
                                                 globalPreviousState, globalCurrentState,
                                                 globalPreviousState, globalCurrentState,
                                                 mapper);
    }
}


text:
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "context_processors_test.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

redpajama_set_name: RedPajamaGithub


text:
package com.xiaomi.miui.analyticstracker;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class a extends SQLiteOpenHelper
{

    private static final String a = "create table %s(_id integer primary key autoincrement, type integer, event_id text, param text, time text, value text)";
    private String b;

    public a(Context context, String s, String s1, int i)
    {
        super(context, s, null, i);
        b = s1;
    }

    public void onCreate(SQLiteDatabase sqlitedatabase)
    {
        Object aobj[] = new Object[1];
        aobj[0] = b;
        sqlitedatabase.execSQL(String.format("create table %s(_id integer primary key autoincrement, type integer, event_id text, param text, time text, value text)", aobj));
    }

    public void onUpgrade(SQLiteDatabase sqlitedatabase, int i, int j)
    {
    }
}


text:
using Ploeh.AutoFixture;
using Raven.Client.Embedded;
using Should;
using StateMachineTesting.Conditions;
using StateMachineTesting.TestCode;

namespace StateMachineTesting
{
    public class can_persist_state_and_recreate_state_Test : BaseTest
    {
        private static EmbeddableDocumentStore store;
        private static string id = "1";
        private static SimpleState firstState;

        private IFixture _registry;

        public void simple_state_should_be_on()
        {
            firstState.State.Name.ShouldEqual("On");
        }

        public override void FixtureSetup(IFixture registry)
        {
            _registry = registry;

            store = new EmbeddableDocumentStore
            {
                RunInMemory = true
            };
            store.Initialize();

            firstState = new SimpleState(new RavenDbPersister(store));
            firstState.TurnOn(new Lamp
            {
                Name = "Skippy", Id = 1
            });
        }

        public override void FixtureTeardown()
        {
            store.Dispose();
        }
    }
}


text:
using HarshPoint.ObjectModel;
using System;
using System.Linq;
using System.Reflection;
using Xunit;
using Xunit.Abstractions;

namespace HarshPoint.Tests.ObjectModel
{
    public class PropertyValueSourceTracking : SeriloggedTest
    {
        public PropertyValueSourceTracking(ITestOutputHelper output) : base(output)
        {
        }

        [Fact]
        public void PropertySource_is_stored_and_retrieved()
        {
            var target = new Tracker();
            var source = new TestSource();
            var metadata = new HarshObjectMetadata(typeof(Tracker));

            var accessor = metadata.ModelProperties.Single();

            accessor.SetValue(target, "42", source);

            Assert.Equal("42", target.Property);
            Assert.Same(source, accessor.GetValueSource(target));
        }

        private sealed class Tracker : ITrackValueSource
        {
            private readonly PropertyValueSourceTracker _tracker
                = new PropertyValueSourceTracker();

            public String Property
            {
                get; set;
            }

            public PropertyValueSource GetValueSource(PropertyInfo propertyInfo)
                => _tracker.GetValueSource(propertyInfo);

            public void SetValueSource(PropertyInfo propertyInfo, PropertyValueSource source)
            {
                _tracker.SetValueSource(propertyInfo, source);
            }
        }

        private sealed class TestSource : PropertyValueSource { }
    }
}


text:
package xtrememp.util;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Besmir Beqiri
 */
public final class Utilities {

    /**
     * System default locale.
     */
    private static Locale systemLocale;
    private static final Locale SPANISH = new Locale("es");
    /**
     * An array of protocol strings.
     */
    public static final String[] PROTOCOLS = {"http:", "file:", "ftp:", "https:", "ftps:", "jar:"};
    //
    public static final String ZERO_TIMER = "00:00 / 00:00";
    public static final String VISUALIZATION_PANEL = "VISUALIZATION_PANEL";
    public static final String PLAYLIST_MANAGER = "PLAYLIST_MANAGER";
    public static final String DEFAULT_PLAYLIST = "default.xspf";
    //
    public static final int MIN_GAIN = 0;
    public static final int MAX_GAIN = 100;
    //
    public static final Icon APP_256_ICON = getIcon("icon_256.png");
    //
    public static final Icon FOLDER_ICON = getIcon("folder.png");
    public static final Icon FOLDER_REMOTE_ICON = getIcon("folder-remote.png");
    public static final Icon DOCUMENT_OPEN_ICON = getIcon("document-open.png");
    public static final Icon DOCUMENT_SAVE_ICON = getIcon("document-save.png");
    public static final Icon MEDIA_PLAY_ICON = getIcon("media-playback-start.png");
    public static final Icon MEDIA_PAUSE_ICON = getIcon("media-playback-pause.png");
    public static final Icon MEDIA_STOP_ICON = getIcon("media-playback-stop.png");
    public static final Icon MEDIA_PREVIOUS_ICON = getIcon("media-skip-backward.png");
    public static final Icon MEDIA_NEXT_ICON = getIcon("media-skip-forward.png");
    public static final Icon PLAYLIST_REPEAT_NONE_ICON = getIcon("media-playlist-repeat_none.png");
    public static final Icon PLAYLIST_REPEAT_ONE_ICON = getIcon("media-playlist-repeat_one.png");
    public static final Icon PLAYLIST_REPEAT_ALL_ICON = getIcon("media-playlist-repeat_all.png");
    public static final Icon PLAYLIST_SHUFFLE_ICON = getIcon("media-playlist-shuffle.png");
    public static final Icon AUDIO_VOLUME_HIGH_ICON = getIcon("audio-volume-high.png");
    public static final Icon AUDIO_VOLUME_MEDIUM_ICON = getIcon("audio-volume-medium.png");
    public static final Icon AUDIO_VOLUME_LOW_ICON = getIcon("audio-volume-low.png");
    public static final Icon AUDIO_VOLUME_MUTED_ICON = getIcon("audio-volume-muted.png");
    public static final Icon LIST_ADD_ICON = getIcon("list-add.png");
    public static final Icon LIST_REMOVE_ICON = getIcon("list-remove.png");
    public static final Icon EDIT_CLEAR_ICON = getIcon("edit-clear.png");
    public static final Icon GO_UP_ICON = getIcon("go-up.png");
    public static final Icon GO_DOWN_ICON = getIcon("go-down.png");
    public static final Icon GO_PREVIOUS_ICON = getIcon("go-previous.png");
    public static final Icon GO_NEXT_ICON = getIcon("go-next.png");
    public static final Icon MEDIA_INFO_ICON = getIcon("media-info.png");
    public static final Icon VIEW_FULLSCREEN_ICON = getIcon("view-fullscreen.png");
    public static final Icon MENU_ICON = getIcon("menu.png");
    public static final Icon PREFERENCES_SYSTEM_ICON = getIcon("preferences-system.png");
    public static final Icon AUDIO_CARD_ICON = getIcon("audio-card.png");

    /**
     * Close dialog with ESC key.
     *
     * @param dialog a {@link JDialog} instance.
     */
    public static void closeOnEscape(final JDialog dialog) {
        JRootPane rootPane = dialog.getRootPane();
        String escape = "escape";
        InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escape);
        ActionMap actionMap = rootPane.getActionMap();
        actionMap.put(escape, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
    }

    /**
     * @see LanguageBundle#getString(java.lang.String).
     */
    public static String tr(String key) {
        return LanguageBundle.getString(key);
    }

    /**
     * Returns an array of supported locales including the system locale.
     *
     * @return an array of {@link Locale} objects.
     */
    public static Locale[] getLanguages() {
        Locale[] locales = {getSystemLocale(),
            Locale.ENGLISH, Locale.FRENCH, Locale.ITALIAN, SPANISH};
        return locales;
    }

    /**
     * Gets the current value of the default locale for this instance
     * of the Java Virtual Machine.
     *

     * The Java Virtual Machine sets the default locale during startup
     * based on the host environment. This method must be used before
     *

     * {@link Locale#setDefault(java.util.Locale)}
     *

     * method is ever called.
     *
     * @return the default locale for this instance of the Java Virtual Machine.
     */
    public static Locale getSystemLocale() {
        if (systemLocale == null) {
            systemLocale = Locale.getDefault();
        }
        return systemLocale;
    }

    /**
     * Returns a {@link BufferedImage} as the result of decoding
     * an image with the given name.
     *
     * @param name the image name.
     * @return a BufferedImage object, or null.
     */
    public static BufferedImage getImage(String name) {
        BufferedImage image = null;
        if (name != null) {
            try {
                image = ImageIO.read(Utilities.class.getResourceAsStream("/xtrememp/resources/images/" + name));
            } catch (IOException ex) {
                ex.printStackTrace(System.err);
            }
        }
        return image;
    }

    /**
     * Returns an {@link Icon} wrapping the image with the given name.
     *
     * @param name the icon name.
     * @return an {@link Icon} object, or null.
     */
    public static Icon getIcon(String name) {
        return new ImageIcon(getImage(name));
    }

    /**
     * Returns a list containing the application icon images in different sizes.
     *
     * @return a {@link List} object.
     */
    public static List<Image> getIconImages() {
        List<Image> icons = new ArrayList<Image>(3);
        icons.add(getImage("icon_32.png"));
        icons.add(getImage("icon_48.png"));
        icons.add(getImage("icon_64.png"));
        return icons;
    }

    /**
     * Check if the provided {@link String} is null or empty.
     *
     * @param value the {@link String} to check.
     * @return true if the {@link String} is null
     *         or empty, else false.
     */
    public static boolean isNullOrEmpty(String value) {
        if (value != null) {
            return value.isEmpty();
        }
        return true;
    }

    /**
     * Returns a human-readable version of the file size, where the input
     * represents a specific number of bytes.
     *
     * @param size the number of bytes.
     * @return a human-readable display value (includes units).
     */
    public static String byteCountToDisplaySize(long size) {
        double ONE_KiB_D = 1024D;
        double ONE_MiB_D = ONE_KiB_D * ONE_KiB_D;
        double ONE_GiB_D = ONE_KiB_D * ONE_MiB_D;

        StringBuilder sbResult = new StringBuilder();
        NumberFormat sizeFormat = NumberFormat.getNumberInstance();
        sizeFormat.setMinimumFractionDigits(0);
        sizeFormat.setMaximumFractionDigits(2);
        if (size > ONE_GiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_GiB_D)).append(" GiB");
        } else if (size > ONE_MiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_MiB_D)).append(" MiB");
        } else if (size > ONE_KiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_KiB_D)).append(" KiB");
        } else {
            sbResult.append(String.valueOf(size)).append(" bytes");
        }
        return sbResult.toString();
    }

    /**
     * Check if the provided {@link String} start with one supported
     * protocol strings.
     *
     * @param input the {@link String} to check.
     * @return true if the {@link String} start with a protocol,
     *         else false.
     */
    public static boolean startWithProtocol(String input) {
        if (input != null) {
            input = input.toLowerCase();
            for (String protocol : PROTOCOLS) {
                if (input.startsWith(protocol)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Check if the provided {@link String} start with a specified
     * protocol {@link String}.
     *
     * @param input the {@link String} to check.
     * @param protocol the protocol {@link String}.
     * @return true if the {@link String} start with the
     *         specified protocol, else false.
     */
    public static boolean startWithProtocol(String input, String protocol) {
        if (input != null) {
            input = input.toLowerCase();
            if (input.startsWith(protocol)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Counts the number of occurences of a given {@link String} into another
     *
     * @param text the {@link String} to look in
     * @param word the {@link String} to be found into the text
     * @return the number of occurences of the word
     */
    public static int countStringOccur(String text, String word) {
        Matcher matcher = Pattern.compile(Pattern.quote(word)).matcher(text);
        int matches = 0;
        while (matcher.find()) {
            matches++;
        }
        return matches;
    }

    /**
     * Returns a list of strings from a single {@link String} splitted given a pattern
     * (must end with pattern)
     *
     * @param text the {@link String} to split into multiple Strings
     * @param pattern the {@link String} separating each substring
     * @return the list of substrings
     */
    public static String[] stringSplitter(String text, String pattern) {
        List<String> substrings = new ArrayList<String>(6);
        int beginIndex = 0;
        Matcher matcher = Pattern.compile(Pattern.quote(pattern)).matcher(text);
        while (matcher.find()) {
            substrings.add(text.substring(beginIndex, matcher.start()));
            beginIndex = matcher.end();
        }
        return substrings.toArray(new String[]{});
    }
}


text:
#include <windows.h>
#include <stdio.h>
#include <conio.h>

#include "../../api/inc/fmod.hpp"
#include "../../api/inc/fmod_errors.h"

void ERRCHECK(FMOD_RESULT result)
{
    if (result != FMOD_OK)
    {
        printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
        exit(-1);
    }
}

int main(int argc, char *argv[])
{
    FMOD::System     *system;
    FMOD::Sound      *sound;
    FMOD_RESULT       result;
    unsigned int      version;

    /*
        Create a System object and initialize.
    */
    result = FMOD::System_Create(&system);
    ERRCHECK(result);

    result = system->getVersion(&version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }

    result = system->init(1, FMOD_INIT_NORMAL, 0);
    ERRCHECK(result);

    result = system->createStream("../media/wave.mp3", FMOD_OPENONLY | FMOD_ACCURATETIME, 0, &sound);
    ERRCHECK(result);

    printf("===============================================================================\n");
    printf("Offline Decoding Example.  Copyright (c) Firelight Technologies 2004-2011.\n");
    printf("===============================================================================\n");
    printf("\n");
    printf("This program will open wave.mp3 and decode it into wave.raw using the\n");
    printf("Sound::readData function.\n");
    printf("\n");

    /*
        Decode the sound and write it to a .raw file.
    */
    {
        void *data;
        unsigned int length = 0, read;
        unsigned int bytesread;
        FILE *outfp;

        #define CHUNKSIZE 4096

        result = sound->getLength(&length, FMOD_TIMEUNIT_PCMBYTES);
        ERRCHECK(result);

        outfp = fopen("output.raw", "wb");
        if (!outfp)
        {
            printf("Error!  Could not open output.raw output file.\n");
            return 0;
        }

        data = malloc(CHUNKSIZE);
        if (!data)
        {
            printf("Error!  Failed to allocate %d bytes.\n", CHUNKSIZE);
            return 0;
        }

        bytesread = 0;
        do
        {
            result = sound->readData((char *)data, CHUNKSIZE, &read);

            fwrite((char *)data, read, 1, outfp);

            bytesread += read;

            printf("writing %d bytes of %d to output.raw\r", bytesread, length);
        }
        while (result == FMOD_OK && read == CHUNKSIZE);

        /*
            Loop terminates when either
            1. the read function returns an error.  (ie FMOD_ERR_FILE_EOF etc).
            2. the amount requested was different to the amount returned. (somehow got an EOF without the file error, maybe a non stream file format like mod/s3m/xm/it/midi).

            If 'bytesread' is bigger than 'length' then it just means that FMOD miscalculated the size,
            but this will not usually happen if FMOD_ACCURATETIME is used.  (this will give the correct length for VBR formats)
        */

        printf("\n");

        if (outfp)
        {
            fclose(outfp);
        }
    }

    printf("\n");

    /*
        Shut down
    */
    result = sound->release();
    ERRCHECK(result);
    result = system->close();
    ERRCHECK(result);
    result = system->release();
    ERRCHECK(result);

    return 0;
}


text:
package org.globus.tools;

import java.io.File;

import org.globus.common.CoGProperties;
import org.globus.util.Util;

/** Destroys a proxy file.
 *

 * Syntax: java ProxyDestroy [-dryrun][-default] [file1...]
 *         java ProxyDestroy -help\n
 * Options
  * -help | -usage
  *     Displays usage
  * -dryrun
  *     Prints what files would have been destroyed
  * file1 file2 ...
  *     Destroys files listed
 *

 */
public class ProxyDestroy {

    private static final String message =
	"\n" +
	"Syntax: java ProxyDestroy [-dryrun] [file1...]\n" +
	"        java ProxyDestroy -help\n\n" +
	"\tOptions\n" +
	"\t-help | -usage\n" +
	"\t\tDisplays usage\n" +
	"\t-dryrun\n" +
	"\t\tPrints what files would have been destroyed\n" +
	"\tfile1 file2 ...\n" +
	"\t\tDestroys files listed\n\n";

  public static void main(String args[]) {

      boolean dryrun      = false;
      boolean error       = false;
      boolean debug       = false;
      File file           = null;

      for (int i = 0; i < args.length; i++) {
	  if (args[i].equalsIgnoreCase("-dryrun")) {
	      dryrun = true;
	  } else if (args[i].equalsIgnoreCase("-help") ||
		     args[i].equalsIgnoreCase("-usage")) {
	      System.err.println(message);
	      System.exit(1);
	  } else {
	      file = new File(args[i]);
	      if (dryrun) {
		  System.out.println("Would remove " + file.getAbsolutePath());
		  continue;
	      }
	      Util.destroy(file);
	  }
      }

      String fn = CoGProperties.getDefault().getProxyFile();
      if (fn == null) return ;
      file = new File(fn);
      if (dryrun) {
	  System.out.println("Would remove " + file.getAbsolutePath());
	  return;
      }

      Util.destroy(file);
  }

}


text:
package org.jboss.hal.client.configuration.subsystem.jca;

import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.Property;

import static org.jboss.hal.resources.Names.LONG_RUNNING;
import static org.jboss.hal.resources.Names.SHORT_RUNNING;

/** Model node for {@code short-running-threads} and {@code long-running-threads} resources. */
class ThreadPool extends NamedNode {

    private final boolean longRunning;

    ThreadPool(final Property property, final boolean longRunning) {
        super(property);
        this.longRunning = longRunning;
    }

    boolean isLongRunning() {
        return longRunning;
    }

    String getRunningMode() {
        return longRunning ? LONG_RUNNING : SHORT_RUNNING;
    }

    String id() {
        return getName() + "-" + getRunningMode();
    }
}


text:
<!DOCTYPE html>

    <title>Life Cycle Event</title>


text:
package fr.openwide.maven.artifact.notifier.web.application.common.component;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import fr.openwide.core.wicket.markup.html.panel.GenericPanel;
import fr.openwide.core.wicket.more.markup.html.basic.DateLabel;
import fr.openwide.core.wicket.more.markup.html.collection.GenericEntitySortedSetView;
import fr.openwide.core.wicket.more.model.BindingModel;
import fr.openwide.core.wicket.more.model.CollectionToListWrapperModel;
import fr.openwide.core.wicket.more.model.GenericEntityTreeSetModel;
import fr.openwide.core.wicket.more.util.DatePattern;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.Artifact;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.ArtifactVersion;
import fr.openwide.maven.artifact.notifier.core.business.artifact.service.IArtifactService;
import fr.openwide.maven.artifact.notifier.core.business.artifact.service.IArtifactVersionService;
import fr.openwide.maven.artifact.notifier.core.business.statistics.service.IStatisticService;
import fr.openwide.maven.artifact.notifier.core.config.application.MavenArtifactNotifierConfigurer;
import fr.openwide.maven.artifact.notifier.core.util.binding.Binding;
import fr.openwide.maven.artifact.notifier.web.application.artifact.component.ArtifactVersionTagPanel;
import fr.openwide.maven.artifact.notifier.web.application.artifact.page.ArtifactDescriptionPage;

public class StatisticsPanel2 extends GenericPanel<Map<Date, Set<ArtifactVersion>>> {

	private static final long serialVersionUID = 8349879446477301375L;

	@SpringBean
	private IStatisticService statisticService;

	@SpringBean
	private IArtifactService artifactService;

	@SpringBean
	private IArtifactVersionService artifactVersionService;

	@SpringBean
	private MavenArtifactNotifierConfigurer configurer;

	public StatisticsPanel2(String id) {
		super(id);
		setOutputMarkupId(true);

		// Most followed artifacts
		IModel<List<Artifact>> mostFollowedArtifactsModel = new LoadableDetachableModel<List<Artifact>>() {
			private static final long serialVersionUID = 1L;

			@Override
			protected List<Artifact> load() {
				return artifactService.listMostFollowedArtifacts(configurer.getMostFollowedArtifactsLimit());
			}
		};
		add(new ListView<Artifact>("mostFollowedArtifacts", mostFollowedArtifactsModel) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Artifact> item) {
				item.add(ArtifactDescriptionPage.linkDescriptor(item.getModel()).link("artifactId")
						.setBody(BindingModel.of(item.getModel(), Binding.artifact().artifactKey().key())));

				item.add(new Label("followersCount", BindingModel.of(item.getModel(), Binding.artifact().followersCount())));
			}
		});

		// Recent updates
		final IModel<Map<Date, SortedSet<ArtifactVersion>>> artifactVersionLastUpdateDateModel = new LoadableDetachableModel<Map<Date, SortedSet<ArtifactVersion>>>() {
			private static final long serialVersionUID = 1L;

			@Override
			protected Map<Date, SortedSet<ArtifactVersion>> load() {
				Map<Date, SortedSet<ArtifactVersion>> result = Maps.newTreeMap(Collections.reverseOrder());
				List<ArtifactVersion> versionList = artifactVersionService.listRecentReleases(configurer.getLastUpdatesArtifactsLimit());

				Date previousDate = null;
				int daysCount = 0;
				for (ArtifactVersion version : versionList) {
					if (previousDate == null || !DateUtils.isSameDay(previousDate, version.getLastUpdateDate())) {
						if (daysCount >= configurer.getLastUpdatesDaysLimit()) {
							break;
						}
						previousDate = version.getLastUpdateDate();
						result.put(previousDate, Sets.<ArtifactVersion>newTreeSet());
						daysCount++;
					}
					result.get(previousDate).add(version);
				}
				return result;
			}
		};

		IModel<List<Date>> wrapperModel = CollectionToListWrapperModel.of(artifactVersionLastUpdateDateModel.getObject().keySet());

		add(new ListView<Date>("dayList", wrapperModel) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Date> item) {
				Date day = item.getModelObject();
				SortedSet<ArtifactVersion> versionSet = artifactVersionLastUpdateDateModel.getObject().get(day);

				Label dayLabel = new DateLabel("day", Model.of(day), DatePattern.SHORT_DATE);
				if (versionSet == null) {
					dayLabel = new Label("day");
					versionSet = Sets.newTreeSet();
				}

				IModel<SortedSet<ArtifactVersion>> versionSetModel = GenericEntityTreeSetModel.of(ArtifactVersion.class);
				versionSetModel.setObject(versionSet);

				// Day label
				item.add(dayLabel);
				item.add(new GenericEntitySortedSetView<ArtifactVersion>("notificationList", versionSetModel) {
					private static final long serialVersionUID = 1L;

					@Override
					protected void populateItem(Item<ArtifactVersion> item) {
						final IModel<ArtifactVersion> notificationModel = item.getModel();
						final IModel<Artifact> artifactModel = BindingModel.of(notificationModel,
								Binding.artifactVersion().artifact());

						// Artifact link
						Link<Void> artifactLink = ArtifactDescriptionPage
								.linkDescriptor(artifactModel)
								.link("artifactLink");
						artifactLink.add(new Label("id", BindingModel.of(artifactModel, Binding.artifact().artifactKey().key())));
						item.add(artifactLink);

						// Version tag
						item.add(new ArtifactVersionTagPanel("version", BindingModel.of(notificationModel,  Binding.artifactVersion().version())));
					}
				});
			}
		});
	}
}


text:
class Spree::UsersController < Spree::StoreController
  skip_before_filter :set_current_order, :only => :show
  prepend_before_filter :load_object, :only => [:show, :edit, :update]
  prepend_before_filter :authorize_actions, :only => :new

  include Spree::Core::ControllerHelpers

  def show
    @orders = @user.orders.complete.order('completed_at desc')
  end

  def create
    @user = Spree::User.new(user_params)
    if @user.save

      if current_order
        session[:guest_token] = nil
      end

      redirect_back_or_default(root_url)
    else
      render :new
    end
  end

  def update
    if @user.update_attributes(user_params)
      if params[:user][:password].present?
        # this logic needed b/c devise wants to log us out after password changes
        user = Spree::User.reset_password_by_token(params[:user])
        sign_in(@user, :event => :authentication, :bypass => !Spree::Auth::Config[:signout_after_password_change])
      end
      redirect_to spree.account_url, :notice => Spree.t(:account_updated)
    else
      render :edit
    end
  end

  private
    def user_params
      params.require(:user).permit(Spree::PermittedAttributes.user_attributes)
    end

    def load_object
      @user ||= spree_current_user
      authorize! params[:action].to_sym, @user
    end

    def authorize_actions
      authorize! params[:action].to_sym, Spree::User.new
    end

    def accurate_title
      Spree.t(:my_account)
    end
end


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AMPjs</title>
<meta name="description" content="AMP Javascript Library">
<meta name="keywords" content="AMP,js,javascript,library">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name=viewport content="width=device-width, initial-scale=1">
<meta name="format-detection" content="telephone=no,address=no,email=no">

<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="./assets/css/font-awesome.min.css" media="all">
<link rel="stylesheet" href="./assets/css/global.css" media="all">
<link rel="stylesheet" href="./assets/jquery.ex-code-prettify/jquery.ex-code-prettify.css" media="all">

AMPjs DEMO

AMP.Is API Reference

型, OS, デバイス, ブラウザの判定しBoolean値を返します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('-------------------- AMP.Is --------------------');

// 型判定
var obj = {a: 0};
console.log('isObject : {a: 0} : ' + AMP.isObject(obj));
console.log('isPlainObject : {a: 0} : ' + AMP.isPlainObject(obj));
console.log('isArray : {a: 0} : ' + AMP.isArray(obj));

// 下記のOS, デバイス, ブラウザ判定は、ショートハンドとして用意しています。
// OS判定
// 引数リスト: windows, windowsPhone, mac, ios, android
console.log('isOS : windows : ' + AMP.isOS('windows'));

// Device判定
// 引数リスト: pc, sd, smartdevice, sp, smartphone, tb, tablet, iphone, ipad, ipod, androidphone, androidtablet
console.log('isDevice : smartdevice : ' + AMP.isDevice('smartdevice'));

// Browser判定
// 引数リスト: ie, edge, chrome, safari, firefox, opera, mobileSafari, android, webkit
console.log('isBrowser : ie : ' + AMP.isBrowser('ie'));
</textarea>

AMP.Has API Reference

ブラウザ機能の判定しBoolean値を返します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.Has --------------------');

console.log('Geolocation機能 : ' + AMP.hasGeolocation());
console.log('PushState機能 : ' + AMP.hasPushState());
console.log('requestAnimationFrame機能の有無 : ' + AMP.hasRAF());
console.log('Location Hashの有無 : ' + AMP.hasHash());
</textarea>

AMP.Has API Reference

ブラウザ機能の判定しBoolean値を返します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- HAS START --------------------');

console.log('Geolocation機能 : ' + AMP.hasGeolocation());
console.log('PushState機能 : ' + AMP.hasPushState());
console.log('requestAnimationFrame機能の有無 : ' + AMP.hasRAF());
console.log('Location Hashの有無 : ' + AMP.hasHash());
</textarea>

AMP.Location API Reference

Locationオブジェクトを扱います。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.Location --------------------');

// hashを取得し、配列にして返す
console.log('getHash', AMP.getHash());

// リクエストパラメータ値を連想配列として取得
console.log('queryHashMap', AMP.queryHashMap());
</textarea>

AMP.Array API Reference

配列を扱います。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.Array --------------------');

// argumentsを配列に変換(引数指定でスライス可能)
(function(){
	console.log('argsToArray : ' + AMP.argsToArray(arguments, 1));
}('arg01', 'arg02', 'arg03'));

// 配列をシャッフルして新しい配列を返す
console.log('shuffle : ' + AMP.shuffle([0,1,2,3,4,5]));
</textarea>

AMP.String API Reference

文字列を扱います。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.String --------------------');

// 空白文字の削除
console.log('AMP.removeSpace(\'Test01 Test02 Test03\') : ' + AMP.removeSpace('Test01 Test02 Test03'));

// 文字列全置換
console.log("AMP.repraceAll('Test01 Test02 Test03', '0', '_') : " + AMP.repraceAll('Test01 Test02 Test03', '0', '_'));
</textarea>

AMP.Extend API Reference

オブジェクト拡張、クラス継承などの機能を提供します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.Extend --------------------');

// ### クラスの継承 ###
// 親クラス
function Parent(){}
Parent.prototype.firstName = 'Fujiwara';

// 子クラスを定義
function Child(){};

// 継承(可変長引数で多重継承可能)
AMP.inherits(Child, Parent);

// 子クラスのプロパティ・メソッド定義
Child.prototype.secondName = 'Yoshihito';
Child.prototype.callName = function(){
	console.log(this.firstName + this.secondName);
};

console.log('child class instance', new Child());

// ### クラスの拡張 ###
function Fujiwara(){}

// 拡張メソッドをエクスポート
Fujiwara.extend = AMP._extend;

Fujiwara.prototype.firstName = 'Fujiwara';
Fujiwara.prototype.secondName = 'Yoshihito';
Fujiwara.prototype.callName = function(){
	console.log(this.firstName + this.secondName);
};

// クラスを拡張
var Fujiwara2 = Fujiwara.extend();
Fujiwara2.prototype.walk = function(){};

// or

var Fujiwara2 = Fujiwara.extend({
	walk: function(){}
});
</textarea>

AMP.Utility API Reference

Utility機能を提供します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

<textarea class="code script" data-ex-code-prettify-param="{codeType:'script', autoRun:true}">
console.log('\n-------------------- AMP.Utility --------------------');

// 関数名の取得
function HOGE(){}
console.log('関数名の取得', AMP.getFunctionName(HOGE));

// 乱数の生成
console.log('乱数の生成', AMP.random(0, 100, true));
</textarea>

AMP.Fallback API Reference

ブラウザの差異を吸収する為の機能を提供します。

メソッド一覧、引数に関して詳しくはAPIを参照してください。

Copyright © 2014 Yoshihito Fujiwara


text:
@implementation BezierPathView

- (void)setPath:(UIBezierPath *)path {
    _path = path;
    [self setNeedsDisplay];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    [self.path stroke];
}

@end


text:
define(
//begin v1.x content
({
	"collapse": "Comprimi la barra degli strumenti dell'editor",
	"expand": "Espandi la barra degli strumenti dell'editor"
})

//end v1.x content
);


text:
/**
 * @author Igor V. Stolyarov
 * @version $Revision$
 */

package awt.java.awt.image;

import java.util.Hashtable;

import org.apache.harmony.awt.internal.nls.Messages;

/**
 * The ReplicateScaleFilter class scales an source image by replicating rows and
 * columns of pixels to scale up or omitting rows and columns of pixels to scale
 * down.
 *
 * @since Android 1.0
 */
public class ReplicateScaleFilter extends ImageFilter {

    /**
     * The width of a source image.
     */
    protected int srcWidth;

    /**
     * The height of a source image.
     */
    protected int srcHeight;

    /**
     * The width of a destination image.
     */
    protected int destWidth;

    /**
     * The height of a destination image.
     */
    protected int destHeight;

    /**
     * The integer array of source rows.
     */
    protected int[] srcrows;

    /**
     * The integer array of source columns.
     */
    protected int[] srccols;

    /**
     * An Object (byte array with a destination width) provides a row of pixel
     * data to the ImageConsumer.
     */
    protected Object outpixbuf;

    /**
     * Instantiates a new ReplicateScaleFilter that filters the image with the
     * specified width and height.
     *
     * @param width
     *            the width of scaled image.
     * @param height
     *            the height of scaled image.
     */
    public ReplicateScaleFilter(int width, int height) {
        if (width == 0 || height == 0) {
            // awt.234=Width or Height equals zero
            throw new IllegalArgumentException(Messages.getString("awt.234")); //$NON-NLS-1$
        }

        this.destWidth = width;
        this.destHeight = height;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setProperties(Hashtable<?, ?> props) {
        Hashtable<Object, Object> fprops;
        if (props == null) {
            fprops = new Hashtable<Object, Object>();
        } else {
            fprops = (Hashtable<Object, Object>)props.clone();
        }
        String propName = "Rescale Filters"; //$NON-NLS-1$
        String prop = "destWidth=" + destWidth + "; " + //$NON-NLS-1$ //$NON-NLS-2$
                "destHeight=" + destHeight; //$NON-NLS-1$
        Object o = fprops.get(propName);
        if (o != null) {
            if (o instanceof String) {
                prop = (String)o + "; " + prop; //$NON-NLS-1$
            } else {
                prop = o.toString() + "; " + prop; //$NON-NLS-1$
            }
        }
        fprops.put(propName, prop);
        consumer.setProperties(fprops);
    }

    // setPixels methods produce pixels according to Java API Spacification

    @Override
    public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off,
            int scansize) {

        if (srccols == null) {
            initArrays();
        }
        int buff[];
        if (outpixbuf == null || !(outpixbuf instanceof int[])) {
            buff = new int[destWidth];
            outpixbuf = buff;
        } else {
            buff = (int[])outpixbuf;
        }

        int wa = (srcWidth - 1) >>> 1;
        int ha = (srcHeight - 1) >>> 1;
        int dstX = (x * destWidth + wa) / srcWidth;
        int dstY = (y * destHeight + ha) / srcHeight;

        int sx, sy, dx, dy;
        dy = dstY;
        while ((dy < destHeight) && ((sy = srcrows[dy]) < y + h)) {
            dx = dstX;
            int srcOff = off + (sy - y) * scansize;
            while ((dx < destWidth) && ((sx = srccols[dx]) < x + w)) {
                buff[dx] = pixels[srcOff + (sx - x)];
                dx++;
            }

            consumer.setPixels(dstX, dy, dx - dstX, 1, model, buff, dstX, destWidth);
            dy++;
        }
    }

    @Override
    public void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int off,
            int scansize) {

        if (srccols == null) {
            initArrays();
        }
        byte buff[];
        if (outpixbuf == null || !(outpixbuf instanceof byte[])) {
            buff = new byte[destWidth];
            outpixbuf = buff;
        } else {
            buff = (byte[])outpixbuf;
        }

        int wa = (srcWidth - 1) >>> 1;
        int ha = (srcHeight - 1) >>> 1;
        int dstX = (x * destWidth + wa) / srcWidth;
        int dstY = (y * destHeight + ha) / srcHeight;

        int sx, sy, dx, dy;
        dy = dstY;
        while ((dy < destHeight) && ((sy = srcrows[dy]) < y + h)) {
            dx = dstX;
            int srcOff = off + (sy - y) * scansize;
            while ((dx < destWidth) && ((sx = srccols[dx]) < x + w)) {
                buff[dx] = pixels[srcOff + (sx - x)];
                dx++;
            }

            consumer.setPixels(dstX, dy, dx - dstX, 1, model, buff, dstX, destWidth);
            dy++;
        }
    }

    @Override
    public void setDimensions(int w, int h) {
        srcWidth = w;
        srcHeight = h;

        if (destWidth < 0 && destHeight < 0) {
            destWidth = srcWidth;
            destHeight = srcHeight;
        } else if (destWidth < 0) {
            destWidth = destHeight * srcWidth / srcHeight;
        } else if (destHeight < 0) {
            destHeight = destWidth * srcHeight / srcWidth;
        }
        consumer.setDimensions(destWidth, destHeight);
    }

    /**
     * Initialization of srccols and srcrows arrays.
     */
    private void initArrays() {
        if ((destWidth < 0) || (destHeight < 0)) {
            throw new IndexOutOfBoundsException();
        }

        srccols = new int[destWidth];
        int ca = srcWidth >>> 1;
        for (int i = 0; i < destWidth; i++) {
            srccols[i] = (i * srcWidth + ca) / destWidth;
        }

        srcrows = new int[destHeight];
        int ra = srcHeight >>> 1;
        for (int i = 0; i < destHeight; i++) {
            srcrows[i] = (i * srcHeight + ra) / destHeight;
        }
    }

}


text:
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';
import { assert } from '@ember/debug';

import {
  computed,
  get,
  getProperties,
  getWithDefault,
  set
} from '@ember/object';

import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import { capitalize } from '@ember/string';
import { typeOf } from '@ember/utils';

import ScrollMagicResponsiveMixin from 'ember-scrollmagic/mixins/components/responsive-mixin';

export default Mixin.create(
  ScrollMagicResponsiveMixin, {

  scrollMagic: service(),

  scrollController: computed(function() {
    return get(this, 'scrollMagic').getController();
  }),

  availableSceneOptions: computed(function() {
    return A([
      'duration', 'loglevel', 'offset', 'reverse', 'triggerElement', 'triggerHook'
    ]);
  }),

  defaultOptions: computed(function() {
    return {
      duration: `100%`,
      triggerHook: `onEnter`,
      triggerElement: this.element
    };
  }),

  sceneOptions: computed(function() {
    return {};
  }),

  mergedOptions: computed('defaultOptions', 'sceneOptions', function() {
    let { defaultOptions, sceneOptions } = getProperties(this, 'defaultOptions', 'sceneOptions');
    if (!defaultOptions || !sceneOptions) { return; }
    return assign({}, defaultOptions, sceneOptions);
  }),

  setOrRemoveScene() {
    let scene = get(this, 'scene'),
        match = this.isActiveMediaQuery();

    if (match && !scene) {
      this.setScene();
    } else if (!match && scene) {
      this.removeScene();
    }
  },

  setScene() {
    let scene = this.setupScene();

    this.addIndicators(scene);
    this.addSceneEventHandlers(scene);

    set(this, 'scene', scene);

    this.addScene();
  },

  addScene() {
    let controller = get(this, 'scrollController'),
        scene = get(this, 'scene');

    controller.addScene(scene);
  },

  setupScene() {
    assert(`No setupScene defined.`);
  },

  updateScene(changedValues) {
    let scene = get(this, 'scene');

    Object.keys(changedValues).forEach(key => {
      let updateFunc = scene[key],
          value = changedValues[key];

      if (typeOf(updateFunc) === 'function') {
        updateFunc(value);
      }
    });

    scene.refresh();
  },

  removeScene() {
    let scene = get(this, 'scene');
    if (scene) {
      this.removeSceneEventHandlers(scene);
      this.removeSceneProps(scene);
      scene.remove();
      set(this, 'scene', null);
    }
  },

  addIndicators(scene) {
    let indicators = getWithDefault(this, 'indicators', false),
        type = typeOf(indicators);

    if (indicators === true || type === 'object') {
      let options = type === 'object' ? JSON.parse(JSON.stringify(indicators)) : {};
      scene.addIndicators(options);
    }
  },

  sceneEvents: computed(function() {
    return ['change', 'update', 'progress', 'start', 'end', 'enter', 'leave'];
  }),

  onSceneChange() {},
  onSceneUpdate() {},
  onSceneProgress() {},
  onSceneStart() {},
  onSceneEnd() {},
  onSceneEnter() {},
  onSceneLeave() {},

  addSceneEventHandlers(scene) {
    get(this, 'sceneEvents').forEach(key => {
      let action = get(this, `onScene${capitalize(key)}`);
      scene.on(`${key}.${this.elementId}`, action);
    });

  },

  removeSceneEventHandlers(scene) {
    get(this, 'sceneEvents').forEach(key => {
      scene.off(`${key}.${this.elementId}`);
    });
  },

  removeSceneProps() {
    this.$().removeAttr('style');
  },

  didRender() {
    this._super(...arguments);
    this.setOrRemoveScene();
  },

  didReceiveAttrs() {
    this._super(...arguments);
    let availableSceneOptions = get(this, 'availableSceneOptions'),
        sceneOptions = get(this, 'sceneOptions'),
        scene = get(this, 'scene');

    if (!sceneOptions || get(this, 'isDestroyed')) { return; }

    let newValues = availableSceneOptions.reduce((values, key) => {
      let value = get(this, key);
      values[key] = value;
      return values;
    }, {});

    let changedValues = {};

    Object.keys(newValues).forEach(key => {
      let value = newValues[key];
      if (value !== sceneOptions[key]) {
        sceneOptions[key] = value;
        changedValues[key] = value;
      }
    });

    set(this, 'sceneOptions', sceneOptions);

    if (get(this, 'sceneInitialized')) {
      if (scene) {
        this.updateScene(changedValues);
      } else {
        this.setScene();
      }

    }
  },

  willDestroyElement() {
    this._super(...arguments);
    this.removeScene();
  }

});


text:
static bool has_aux(const char* key,list e) {
  while(e != NULL) {
    if(strcmp(key,((KVpair*)e->head)->key) == 0) return true;
    e = e->tail;
  }
  return false;
}

bool has(const char* key,Environment e) {
  bool result;
  switch(e.type) {
    case GLOBAL:
      result = has_aux(key,e.typedata.global);
      break;
    case INNER:
      result = has_aux(key,e.typedata.inner.inner->kvpairs) || has(key,*e.typedata.inner.outer);
      break;
  }
  return result;
}

static nObj* get_aux(const char* key,list* e) {
  if((*e) == NULL) {
    KVpair* new = malloc(sizeof(KVpair));
    new->key = malloc(strlen(key)+1);
    strcpy(new->key,key);
    new->value = NULL;
    prepend(new,e);
    return &new->value;
  } else if(strcmp(key,((KVpair*)(*e)->head)->key) != 0) { //Different keys
    return get_aux(key,&(*e)->tail);
  } else {
    return &((KVpair*)(*e)->head)->value;
  }
}

nObj* get(const char* key,Environment *e) {
  nObj* result;
  switch(e->type) {
    case GLOBAL:
      result = get_aux(key,&e->typedata.global);
      break;
    case INNER:
      if(has_aux(key,e->typedata.inner.inner->kvpairs)) { //Variable exists inside scope
        result = get_aux(key,&e->typedata.inner.inner->kvpairs);
      } else if(has(key,*e->typedata.inner.outer)) { //Variable exists outside scope
        result = get(key,e->typedata.inner.outer);
      } else { //Variable doesn't exist
        result = get_aux(key,&e->typedata.inner.inner->kvpairs);
      }
      break;
  }
  return result;
}

nObj* get_inner(const char* key,Environment *e) {
  nObj* result;
  switch(e->type) {
    case INNER:
      result = get_aux(key,&e->typedata.inner.inner->kvpairs);
      break;
    default:
      puts("Unsupported type for 'get_inner'.");
      exit(1);
  }
  return result;
}

static void freeKV(void* kv) {
  KVpair* k = (KVpair*)kv;
  free_nObj(k->value);
  free(k->key);
  free(kv);
}

static void free_env_aux(list e) {
  delWith(e,freeKV);
}

void free_env(Environment *e) {
  if(!e) return;
  switch(e->type) {
    case GLOBAL:
      free_env_aux(e->typedata.global);
      break;
    case INNER:
      if(e->typedata.inner.inner->refcount == 1) { //this is the last reference to it
        free_env_aux(e->typedata.inner.inner->kvpairs);
        free(e->typedata.inner.inner);
        if(e->typedata.inner.outer->type != GLOBAL) free_env(e->typedata.inner.outer); //one less ref
        free(e);
      } else {
        e->typedata.inner.inner->refcount--;
      }
      break;
  }
}

Environment new_global() {
  Environment result;
  result.type = GLOBAL;
  result.typedata.global = NULL;
  return result;
}

Environment* new_inner(Environment *outer) {
  Environment *result = malloc(sizeof(Environment));
  result->type = INNER;
  result->typedata.inner.inner = malloc(sizeof(Namespace));
  result->typedata.inner.inner->refcount = 1;
  result->typedata.inner.inner->kvpairs = NULL;
  result->typedata.inner.outer = outer;
  return result;
}

Environment* new_closure(Environment *outer) {
  Environment* result = new_inner(outer);
  while(outer->type == INNER) { //Increase reference counts
    outer->typedata.inner.inner->refcount++;
    outer = outer->typedata.inner.outer;
  }
  return result;
}


text:
package org.pentaho.di.core.logging;

import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.trans.HasDatabasesInterface;

public interface LogTablePluginInterface extends LogTableInterface {

  public enum TableType {
    JOB, TRANS;
  }

  public TableType getType();

  public String getLogTablePluginUIClassname();

  public void setContext( VariableSpace space, HasDatabasesInterface jobMeta );

  // Otherwise identical to the log table interface.

}


text:
<?php

class Ithemes_Sync_Verb_ITSEC_Get_Everything extends Ithemes_Sync_Verb {

	public static $name = 'itsec-get-everything';
	public static $description = 'Retrieve iThemes Security Status and other information.';

	private $default_arguments = array();

	public function run( $arguments ) {

		global $itsec_sync;

		$modules        = $itsec_sync->get_modules();
		$module_results = array();

		//return $modules;

		foreach ( $modules as $name => $module ) {

			if ( isset( $module['verbs'] ) && isset( $module['path'] ) && isset( $module['everything'] ) && isset( $module['verbs'][$module['everything']] ) ) {

				$class = $module['verbs'][$module['everything']];

				if ( ! class_exists( $class ) ) {

					require( trailingslashit( $module['path'] ) . 'class-ithemes-sync-verb-' . $module['everything'] . '.php' );

				}

				$obj = new $class;

				$module_results[$name] = $obj->run( array() );

			}

		}

		return array_merge( array(
			                    'api' => '0',
		                    ),
		                    $module_results
		);

	}

}


text:
require "spec_helper"

describe Spree::CheckoutController do
  it 'should create a new payment on state payment' do
    pending "@TODO:Implement"
  end
  it 'should render its own template' do
    pending "@TODO:Implement"
  end
end


text:
package net.jcip.examples;

import java.util.ArrayList;
import java.util.List;

/**
 * SingleThreadRendere
 * <p/>
 * Rendering page elements sequentially
 *
 * @author Brian Goetz and Tim Peierls
 */
public abstract class SingleThreadRenderer {
    void renderPage(CharSequence source) {
        renderText(source);
        List<ImageData> imageData = new ArrayList<ImageData>();
        for (ImageInfo imageInfo : scanForImageInfo(source))
            imageData.add(imageInfo.downloadImage());
        for (ImageData data : imageData)
            renderImage(data);
    }

    interface ImageData {
    }

    interface ImageInfo {
        ImageData downloadImage();
    }

    abstract void renderText(CharSequence s);
    abstract List<ImageInfo> scanForImageInfo(CharSequence s);
    abstract void renderImage(ImageData i);
}


text:
<?php
/** @var common\models\Meme $meme */
use common\helpers\Tools;

?>

                        <iframe class="mbr-embedded-video" src="<?= $meme->url; ?>" width="1280" height="720" frameborder="0" allowfullscreen>

MOST POPULAR MEME

<?= $meme->name; ?> By <?= $meme->getAuthorNameOfTheOriginalMeme() ?>

                            <?= Tools::ulWithLink($meme->originMemeVidmage->vidmage->getAllNm('vidmageTags', 'tag'), 'tag', true) ?>

                            <?= Tools::ulWithLink($meme->originMemeVidmage->vidmage->getAllNm('vidmageCategories', 'category'), 'channel', true) ?>

<?= $meme->description ?>

<a class="mbr-buttons__btn btn btn-lg btn-default" href="<?= $meme->siteUrl ?>">Watch Meme


text:
import { ACTION_PREFIX } from '../config';

// API
// REDUCER MOUNT POINT
const reducerMountPoint = 'idle';
// ACTIONS
export const SET_IDLE = `${ACTION_PREFIX}SET_IDLE`;
// ACTION CREATOR VALIDATORS
const validIdle = value =>
  !(value === undefined || typeof value !== 'boolean');
// SCHEMA
// REDUCERS
export default (state = true, action) => {
  switch (action.type) {
    case SET_IDLE:
      return action.value;
    default:
      return state;
  }
};
// ACCESSORS
export const getIdle = (state) => state[reducerMountPoint];
// ACTION CREATORS
export const setIdle = (value) => {
  if (!validIdle(value)) throw new Error();
  return ({
    type: SET_IDLE,
    value,
  });
};


text:
<project name="Smooks for Mule 2.x - EDI to Java example" default="install" basedir=".">

	<property environment="env" />

	<property name="mule.home" value="${env.MULE_HOME}" />

	<target name="check-mule-home">

		<fail message="MULE_HOME environment variable not set" unless="mule.home" />

		<fail message="MULE_HOME '${mule.home}' does not exist.">
			<condition>
				<not>
					<available file="${mule.home}" type="dir" />
				</not>
			</condition>
		</fail>

	</target>

	<target name="install" depends="check-mule-home">

		<copy todir="${mule.home}/lib/user">
			<fileset dir="lib/user" />
		</copy>

	</target>

</project>


text:
translating by zyk2290

Two great uses for the cp command: Bash shortcuts
============================================================

### Here's how to streamline the backup and synchronize functions of the cp command.

![Two great uses for the cp command: Bash shortcuts ](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/yearbook-haff-rx-linux-file-lead_0.png?itok=-i0NNfDC)

>Image by : [Internet Archive Book Images][6]. Modified by Opensource.com. CC BY-SA 4.0

Last July, I wrote about [two great uses for the cp command][7]: making a backup of a file, and synchronizing a secondary copy of a folder.

Having discovered these great utilities, I find that they are more verbose than necessary, so I created shortcuts to them in my Bash shell startup script. I thought I'd share these shortcuts in case they are useful to others or could offer inspiration to Bash users who haven't quite taken on aliases or shell functions.

### Updating a second copy of a folder – Bash alias

The general pattern for updating a second copy of a folder with cp is:

```
cp -r -u -v SOURCE-FOLDER DESTINATION-DIRECTORY
```

I can easily remember the -r option because I use it often when copying folders around. I can probably, with some more effort, remember -v, and with even more effort, -u (is it "update" or "synchronize" or…).

Or I can just use the [alias capability in Bash][8] to convert the cp command and options to something more memorable, like this:

```
alias sync='cp -r -u -v'
```

```
sync Pictures /media/me/4388-E5FE
```

Not sure if you already have a sync alias defined? You can list all your currently defined aliases by typing the word alias at the command prompt in your terminal window.

Like this so much you just want to start using it right away? Open a terminal window and type:

```
echo "alias sync='cp -r -u -v'" >> ~/.bash_aliases
```

```
me@mymachine~$ alias

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

alias egrep='egrep --color=auto'

alias fgrep='fgrep --color=auto'

alias grep='grep --color=auto'

alias gvm='sdk'

alias l='ls -CF'

alias la='ls -A'

alias ll='ls -alF'

alias ls='ls --color=auto'

alias sync='cp -r -u -v'

me@mymachine:~$
```

### Making versioned backups – Bash function

The general pattern for making a backup of a file with cp is:

```
cp --force --backup=numbered WORKING-FILE BACKED-UP-FILE
```

Besides remembering the options to the cp command, we also need to remember to repeat the WORKING-FILE name a second time. But why repeat ourselves when [a Bash function][9] can take care of that overhead for us, like this:

Again, you can save this to your .bash_aliases file in your home directory.

```
function backup {

    if [ $# -ne 1 ]; then

        echo "Usage: $0 filename"

    elif [ -f $1 ] ; then

        echo "cp --force --backup=numbered $1 $1"

        cp --force --backup=numbered $1 $1

    else

        echo "$0: $1 is not a file"

    fi

}
```

The first if statement checks to make sure that only one argument is provided to the function, otherwise printing the correct usage with the echo command.

The elif statement checks to make sure the argument provided is a file, and if so, it (verbosely) uses the second echo to print the cp command to be used and then executes it.

If the single argument is not a file, the third echo prints an error message to that effect.

In my home directory, if I execute the backup command so defined on the file checkCounts.sql, I see that backup creates a file called checkCounts.sql.~1~. If I execute it once more, I see a new file checkCounts.sql.~2~.

Success! As planned, I can go on editing checkCounts.sql, but if I take a snapshot of it every so often with backup, I can return to the most recent snapshot should I run into trouble.

At some point, it's better to start using git for version control, but backup as defined above is a nice cheap tool when you need to create snapshots but you're not ready for git.

### Conclusion

In my last article, I promised you that repetitive tasks can often be easily streamlined through the use of shell scripts, shell functions, and shell aliases.

Here I've shown concrete examples of the use of shell aliases and shell functions to streamline the synchronize and backup functionality of the cp command. If you'd like to learn more about this, check out the two articles cited above: [How to save keystrokes at the command line with alias][10] and [Shell scripting: An introduction to the shift method and custom functions][11], written by my colleagues Greg and Seth, respectively.

### About the author

 [![](https://opensource.com/sites/default/files/styles/profile_pictures/public/clh_portrait2.jpg?itok=V1V-YAtY)][13] Chris Hermansen

 Engaged in computing since graduating from the University of British Columbia in 1978, I have been a full-time Linux user since 2005 and a full-time Solaris, SunOS and UNIX System V user before that. On the technical side of things, I have spent a great deal of my career doing data analysis; especially spatial data analysis. I have a substantial amount of programming experience in relation to data analysis, using awk, Python, PostgreSQL, PostGIS and lately Groovy. I have also built a few... [more about Chris Hermansen][14]

--------------------------------------------------------------------------------

via: https://opensource.com/article/18/1/two-great-uses-cp-command-update

作者:[Chris Hermansen][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://opensource.com/users/clhermansen
[1]:https://opensource.com/users/clhermansen
[2]:https://opensource.com/users/clhermansen
[3]:https://opensource.com/user/37806/feed
[4]:https://opensource.com/article/18/1/two-great-uses-cp-command-update?rate=J_7R7wSPbukG9y8jrqZt3EqANfYtVAwZzzpopYiH3C8
[5]:https://opensource.com/article/18/1/two-great-uses-cp-command-update#comments
[6]:https://www.flickr.com/photos/internetarchivebookimages/14803082483/in/photolist-oy6EG4-pZR3NZ-i6r3NW-e1tJSX-boBtf7-oeYc7U-o6jFKK-9jNtc3-idt2G9-i7NG1m-ouKjXe-owqviF-92xFBg-ow9e4s-gVVXJN-i1K8Pw-4jybMo-i1rsBr-ouo58Y-ouPRzz-8cGJHK-85Evdk-cru4Ly-rcDWiP-gnaC5B-pAFsuf-hRFPcZ-odvBMz-hRCE7b-mZN3Kt-odHU5a-73dpPp-hUaaAi-owvUMK-otbp7Q-ouySkB-hYAgmJ-owo4UZ-giHgqu-giHpNc-idd9uQ-osAhcf-7vxk63-7vwN65-fQejmk-pTcLgA-otZcmj-fj1aSX-hRzHQk-oyeZfR
[7]:https://opensource.com/article/17/7/two-great-uses-cp-command
[8]:https://opensource.com/article/17/5/introduction-alias-command-line-tool
[9]:https://opensource.com/article/17/1/shell-scripting-shift-method-custom-functions
[10]:https://opensource.com/article/17/5/introduction-alias-command-line-tool
[11]:https://opensource.com/article/17/1/shell-scripting-shift-method-custom-functions
[12]:https://opensource.com/tags/linux
[13]:https://opensource.com/users/clhermansen
[14]:https://opensource.com/users/clhermansen


text:
package newspoints.sfsu.com.newsp_cloud.dropbox;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Activity to carry out all the operations related to DropBox
 */
public class DropboxActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}


text:
wget --quiet http://apt.puppetlabs.com/puppetlabs-release-precise.deb -O /tmp/puppetlabs-release-precise.deb
dpkg -i /tmp/puppetlabs-release-precise.deb
apt-get update
apt-get install -y ruby-json redis-server puppet-common #masterless puppet
sed -i '/templatedir/d' /etc/puppet/puppet.conf
puppet module install sensu/sensu
puppet module install puppetlabs/rabbitmq


text:
package room;

import Primitives.HorizontalPlane;
import Primitives.VerticalXPlane;
import Primitives.VerticalZPlane;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.texture.Texture;
import notmine.Light;
import peripherals.table.Table;
import scene.SceneGraph;
import scene.styling.Chrome;
import scene.styling.Silver;

import java.io.File;

/**
 * Created by vasily on 02/12/15.
 */
public class Room extends SceneGraph{

    private final int SLICES = 40;
    private VerticalXPlane wall;
    private final VerticalXPlane wall2;
    private final VerticalZPlane wall3;
    private final VerticalZPlane wall4;
    private HorizontalPlane floor;
    private final HorizontalPlane roof;

    public Room(GL2 gl, double width, double height, double depth, Light spotlight1, Light spotlight2) {
        super(0,0,0, new Silver());

        //floor
        Texture floorTexture = loadTexture(gl, "textures" + File.separator + "marble03.bmp");
        this.floor = new HorizontalPlane(0, width+2, depth, SLICES*3, SLICES*3, new int[]{0,1,0},
                floorTexture, 2, 2);
        addChild(floor);

        //roof
        Texture ceilingTexture = loadTexture(gl, "textures" + File.separator + "plank01.bmp");
        this.roof = new HorizontalPlane(height, width+2, depth, SLICES, SLICES, new int[]{0,1,0},
                ceilingTexture, 5, 5,
                spotlight1, spotlight2);
        addChild(roof);

        Texture wallTexture = loadTexture(gl, "textures" + File.separator + "snowflake4.jpg");
        //wall1x
        this.wall = new VerticalXPlane(0, 0, 0-(depth/2), width+2, height, SLICES, SLICES, new int[]{0,0,1},
                wallTexture, 8, 3);
        addChild(wall);

        //wall2x
        this.wall2 = new VerticalXPlane(0, 0, 0+(depth/2), width+2, height, SLICES, SLICES, new int[]{0,0,-1},
                wallTexture, 8, 3);
        addChild(wall2);

        //wall3z
        this.wall3 = new VerticalZPlane(0-((width+2)/2), 0, 0, depth, height, SLICES, SLICES, new int[]{1,0,0},
                wallTexture, 12, 3);
        addChild(wall3);

        //wall4z
        this.wall4 = new VerticalZPlane(0+((width+2)/2), 0, 0, depth, height, SLICES, SLICES, new int[]{-1,0,0},
                wallTexture, 12, 3);
        addChild(wall4);

        //3 tables
        Texture tableLegTexture = loadTexture(gl, "textures" + File.separator + "plank01.bmp");
        addChild(new Table(0-(width/10), 0, 0-(depth/10), height, width, SLICES, tableLegTexture, tableLegTexture));

        addChild(new Table(0, 0, 0+(width/8), height, width, SLICES, tableLegTexture, tableLegTexture));

        addChild(new Table(0+(width/10), 0, 0-(depth/10), height, width, SLICES, tableLegTexture, tableLegTexture));
    }

    public void initialiseDisplayLists(GL2 gl){
        floor.initializeDisplayList(gl);
        roof.initializeDisplayList(gl);
        wall.initializeDisplayList(gl);
        wall2.initializeDisplayList(gl);
        wall3.initializeDisplayList(gl);
        wall4.initializeDisplayList(gl);
    }
}


text:
true-random
===========

A drop-in replacement for Python PRNG modules that provides truly random numbers.

Take a look at:

* Modules: `dist`
* Source code: `dev`
* Usage and rationale: `readme.pdf`

Written for the Pennsylvania Junior Academy of Science, 2013.


text:
<?php
require_once('wfUtils.php');
class wfIssues {
	private $db = false;

	//Properties that are serialized on sleep:
	private $updateCalled = false;
	private $issuesTable = '';
	private $newIssues = array();
	public $totalIssues = 0;
	public $totalCriticalIssues = 0;
	public $totalWarningIssues = 0;
	public function __sleep(){ //Same order here as vars above
		return array('updateCalled', 'issuesTable', 'newIssues', 'totalIssues', 'totalCriticalIssues', 'totalWarningIssues');
	}
	public function __construct(){
		global $wpdb;
		$this->issuesTable = $wpdb->base_prefix . 'wfIssues';
	}
	public function __wakeup(){
		$this->db = new wfDB();
	}
	public function addIssue($type, $severity,

		$ignoreP, /* some piece of data used for md5 for permanent ignores */
		$ignoreC, /* some piece of data used for md5 for ignoring until something changes */
		$shortMsg, $longMsg, $templateData
		){

		$ignoreP = md5($ignoreP);
		$ignoreC = md5($ignoreC);
		$rec = $this->getDB()->querySingleRec("select status, ignoreP, ignoreC from " . $this->issuesTable . " where (ignoreP='%s' OR ignoreC='%s')", $ignoreP, $ignoreC);
		if($rec){
			if($rec['status'] == 'new' && ($rec['ignoreC'] == $ignoreC || $rec['ignoreP'] == $ignoreP)){
				if($type != 'file'){ //Filter out duplicate new issues but not infected files because we want to see all infections even if file contents are identical
					return false;
				}
			}

			if($rec['status'] == 'ignoreC' && $rec['ignoreC'] == $ignoreC){ return false; }
			if($rec['status'] == 'ignoreP' && $rec['ignoreP'] == $ignoreP){ return false; }
		}

		if($severity == 1){
			$this->totalCriticalIssues++;
		} else if($severity == 2){
			$this->totalWarningIssues++;
		}
		$this->totalIssues++;
		$this->newIssues[] = array(
			'type' => $type,
			'severity' => $severity,
			'ignoreP' => $ignoreP,
			'ignoreC' => $ignoreC,
			'shortMsg' => $shortMsg,
			'longMsg' => $longMsg,
			'tmplData' => $templateData
			);

		$this->getDB()->queryWrite("insert into " . $this->issuesTable . " (time, status, type, severity, ignoreP, ignoreC, shortMsg, longMsg, data) values (unix_timestamp(), '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')",
			'new',
			$type,
			$severity,
			$ignoreP,
			$ignoreC,
			$shortMsg,
			$longMsg,
			serialize($templateData)
			);
		return true;
	}
	public function deleteIgnored(){
		$this->getDB()->queryWrite("delete from " . $this->issuesTable . " where status='ignoreP' or status='ignoreC'");
	}
	public function deleteNew(){
		$this->getDB()->queryWrite("delete from " . $this->issuesTable . " where status='new'");
	}
	public function ignoreAllNew(){
		$this->getDB()->queryWrite("update " . $this->issuesTable . " set status='ignoreC' where status='new'");
	}
	public function emailNewIssues(){
		$level = wfConfig::getAlertLevel();
		$emails = wfConfig::getAlertEmails();
		$shortSiteURL = preg_replace('/^https?:\/\//i', '', site_url());
		$subject = "[Wordfence Alert] Problems found on $shortSiteURL";

		if(sizeof($emails) < 1){ return; }
		if($level < 1){ return; }
		if($level == 2 && $this->totalCriticalIssues < 1 && $this->totalWarningIssues < 1){ return; }
		if($level == 1 && $this->totalCriticalIssues < 1){ return; }
		$emailedIssues = wfConfig::get_ser('emailedIssuesList', array());
		if(! is_array($emailedIssues)){
			$emailedIssues = array();
		}
		$finalIssues = array();
		foreach($this->newIssues as $newIssue){
			$alreadyEmailed = false;
			foreach($emailedIssues as $emailedIssue){
				if($newIssue['ignoreP'] == $emailedIssue['ignoreP'] || $newIssue['ignoreC'] == $emailedIssue['ignoreC']){
					$alreadyEmailed = true;
					break;
				}
			}
			if(! $alreadyEmailed){
				$finalIssues[] = $newIssue;
			}
		}
		if(sizeof($finalIssues) < 1){ return; }

		$totalWarningIssues = 0;
		$totalCriticalIssues = 0;
		foreach($finalIssues as $i){
			$emailedIssues[] = array( 'ignoreC' => $i['ignoreC'], 'ignoreP' => $i['ignoreP'] );
			if($i['severity'] == 1){
				$totalCriticalIssues++;
			} else if($i['severity'] == 2){
				$totalWarningIssues++;
			}
		}
		wfConfig::set_ser('emailedIssuesList', $emailedIssues);
		if($level == 2 && $totalCriticalIssues < 1 && $totalWarningIssues < 1){ return; }
		if($level == 1 && $totalCriticalIssues < 1){ return; }
		$content = wfUtils::tmpl('email_newIssues.php', array(
			'isPaid' => wfConfig::get('isPaid'),
			'issues' => $finalIssues,
			'totalCriticalIssues' => $totalCriticalIssues,
			'totalWarningIssues' => $totalWarningIssues,
			'level' => $level
			));

		require_once ABSPATH . WPINC . '/class-phpmailer.php';
		require_once ABSPATH . WPINC . '/class-smtp.php';
		$mail = new PHPMailer;

		// Get the site domain and get rid of www.
		$from_email = 'wordpress@' . preg_replace('/^(https?:\/\/(www.)?)(.+?)(\/)?$/', '$3', site_url());

		$mail->From = apply_filters( 'wp_mail_from', $from_email );
		$mail->FromName = apply_filters( 'wp_mail_from_name', 'Wordfence' );

		foreach ($emails as $email) {
			try {
				$mail->addAddress($email);
			} catch (phpmailerException $e) {

			}
		}

		$mail->Subject = $subject;
		$mail->msgHTML($content);

		try {
			$mail->send();
		} catch (phpmailerException $e) {
			// use wp_mail if there's a problem (which uses PHPMailer anyways :P)
			wp_mail(implode(',', $emails), $subject, strip_tags($content));
		}
	}
	public function deleteIssue($id){
		$this->getDB()->queryWrite("delete from " . $this->issuesTable . " where id=%d", $id);
	}
	public function updateIssue($id, $status){ //ignoreC, ignoreP, delete or new
		$currentStatus = $this->getDB()->querySingle("select status from " . $this->issuesTable . " where id=%d", $id);
		if($status == 'delete'){
			$this->getDB()->queryWrite("delete from " . $this->issuesTable . " where id=%d", $id);
		} else if($status == 'ignoreC' || $status == 'ignoreP' || $status == 'new'){
			$this->getDB()->queryWrite("update " . $this->issuesTable . " set status='%s' where id=%d", $status, $id);
		}
	}
	public function getIssueByID($id){
		$rec = $this->getDB()->querySingleRec("select * from " . $this->issuesTable . " where id=%d", $id);
		$rec['data'] = unserialize($rec['data']);
		return $rec;
	}
	public function getIssues(){
		$issues = wfConfig::get('wf_issues', array());
		$ret = array(
			'new' => array(),
			'ignored' => array()
			);
		$q1 = $this->getDB()->querySelect("select * from " . $this->issuesTable . " order by time desc");
		foreach($q1 as $i){
			$i['data'] = unserialize($i['data']);
			$i['timeAgo'] = wfUtils::makeTimeAgo(time() - $i['time']);
			if($i['status'] == 'new'){
				$ret['new'][] = $i;
			} else if($i['status'] == 'ignoreP' || $i['status'] == 'ignoreC'){
				$ret['ignored'][] = $i;
			} else {
				error_log("Issue has bad status: " . $i['status']);
				continue;
			}
		}
		foreach($ret as $status => &$issueList){
			for($i = 0; $i < sizeof($issueList); $i++){
				if($issueList[$i]['type'] == 'file'){
					$localFile = ABSPATH . '/' . preg_replace('/^[\.\/]+/', '', $issueList[$i]['data']['file']);
					if(file_exists($localFile)){
						$issueList[$i]['data']['fileExists'] = true;
					} else {
						$issueList[$i]['data']['fileExists'] = '';
					}
				}
				$issueList[$i]['issueIDX'] = $i;
			}
		}
		return $ret; //array of lists of issues by status
	}
	public function updateSummaryItem($key, $val){
		$arr = wfConfig::get_ser('wf_summaryItems', array());
		$arr[$key] = $val;
		$arr['lastUpdate'] = time();
		wfConfig::set_ser('wf_summaryItems', $arr);
	}
	public function getSummaryItem($key){
		$arr = wfConfig::get_ser('wf_summaryItems', array());
		if(array_key_exists($key, $arr)){
			return $arr[$key];
		} else { return ''; }
	}
	public function summaryUpdateRequired(){
		$last = $this->getSummaryItem('lastUpdate');
		if( (! $last) || (time() - $last > (86400 * 7))){
			return true;
		}
		return false;
	}
	public function getSummaryItems(){
		if(! $this->updateCalled){
			$this->updateCalled = true;
			$this->updateSummaryItems();
		}
		$arr = wfConfig::get_ser('wf_summaryItems', array());
		//$arr['scanTimeAgo'] = wfUtils::makeTimeAgo(sprintf('%.0f', time() - $arr['scanTime']));
		$arr['scanRunning'] = wfUtils::isScanRunning() ? '1' : '0';
		$arr['scheduledScansEnabled'] = wfConfig::get('scheduledScansEnabled');
		$secsToGo = wp_next_scheduled('wordfence_scheduled_scan') - time();
		if($secsToGo < 1){
			$nextRun = 'now';
		} else {
			$nextRun = wfUtils::makeTimeAgo($secsToGo) . ' from now';
		}
		$arr['nextRun'] = $nextRun;

		$arr['totalCritical'] = $this->getDB()->querySingle("select count(*) as cnt from " . $this->issuesTable . " where status='new' and severity=1");
		$arr['totalWarning'] = $this->getDB()->querySingle("select count(*) as cnt from " . $this->issuesTable . " where status='new' and severity=2");

		return $arr;
	}
	private function updateSummaryItems(){
		global $wpdb;
		$dat = array();
		$users = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
		$dat['totalUsers'] = sizeof($users);
		$res1 = $wpdb->get_col("SELECT count(*) as cnt FROM $wpdb->posts where post_type='page' and post_status NOT IN ('auto-draft')"); $dat['totalPages'] = $res1['0'];
		$res1 = $wpdb->get_col("SELECT count(*) as cnt FROM $wpdb->posts where post_type='post' and post_status NOT IN ('auto-draft')"); $dat['totalPosts'] = $res1['0'];
		$res1 = $wpdb->get_col("SELECT count(*) as cnt FROM $wpdb->comments"); $dat['totalComments'] = $res1['0'];
		$res1 = $wpdb->get_col("SELECT count(*) as cnt FROM $wpdb->term_taxonomy where taxonomy='category'"); $dat['totalCategories'] = $res1['0'];
		$res1 = $wpdb->get_col("show tables"); $dat['totalTables'] = sizeof($res1);
		$totalRows = 0;
		foreach($res1 as $table){
			$res2 = $wpdb->get_col("select count(*) from `$table`");
			if(isset($res2[0]) ){
				$totalRows += $res2[0];
			}
		}
		$dat['totalRows'] = $totalRows;
		$arr = wfConfig::get_ser('wf_summaryItems', array());
		foreach($dat as $key => $val){
			$arr[$key] = $val;
		}
		wfConfig::set_ser('wf_summaryItems', $arr);
	}
	public function setScanTimeNow(){
		$this->updateSummaryItem('scanTime', microtime(true));
	}
	public function getScanTime(){
		return $this->getSummaryItem('scanTime');
	}
	private function getDB(){
		if(! $this->db){
			$this->db = new wfDB();
		}
		return $this->db;
	}
}

?>


text:
namespace capnp {
namespace schemas {

CAPNP_DECLARE_SCHEMA(b9c6f99ebf805f2c);
CAPNP_DECLARE_SCHEMA(f264a779fef191ce);

}  // namespace schemas
}  // namespace capnp

namespace capnp {
namespace annotations {

// =======================================================================================

// =======================================================================================

}  // namespace
}  // namespace

#endif  // CAPNP_INCLUDED_bdf87d7bb8304e81_


text:
set -xe

SDK="$1"
MODE=${2-}

DIR="${SDK}"

if [[ ! -z "$LEGACY" ]]; then
  DIR="${SDK}/Legacy${SDK}Quickstart"
fi

if [ "$MODE" == "release_testing" ]; then
  echo "Update podfiles release_testing."
  sed -i "" "s/https:\/\/.*@github.com\/FirebasePrivate\/SpecsTesting.git/https:\/\/github.com\/FirebasePrivate\/SpecsTesting.git/g" quickstart-ios/"${DIR}"/Podfile quickstart-ios/"${DIR}"/Podfile.lock
fi
rm -f quickstart-ios/"${DIR}"/GoogleService-Info.plist


text:
from flask_wtf import Form
from wtforms.fields import StringField
from flask.ext.wtf.html5 import URLField
from wtforms.validators import DataRequired, url

class BookmarkForm(Form):
    url = URLField('The URL for your bookmark', validators=[DataRequired(), url()])
    description = StringField('Add an optional description')

    def validate(self):
        if not self.url.data.startswith("http://") or\
                self.url.data.startswith("https://"):
            self.url.data = "https://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        return True


text: <script type="text/javascript" src="/assets/js/arenda.js?v=0.0.1"></script>


text:
''' Convert the format of disk images used by libvirt domains
    and adapt the domain configuration.

    Currently only support for qemu is implemented.
'''
import sys, os.path, subprocess
import libvirt
import argparse
from lxml import etree

class LibVirtDriveConvert:
    ''' libvirt disk image converter class '''

    DRIVER_TYPES = {
        'qemu' : {
            'formats' : {
                'raw'   : 'raw',
                'qcow2' : 'qcow2',
                'qcow'  : 'qcow',
                'cow'   : 'cow',
                'qed'   : 'qed',
                'vdi'   : 'vdi',
                'vmdk'  : 'vmdk'
            }
        }
    }

    def _get_info_from_dom_disk_nodes(self, dom_disk_nodes, dom_name):
        ''' Extract disk information from XML node definition.

        :param dom_disk_nodes: array of XML disk-elements
        :param dom_name: domain the entries belong to
        :returns: [{'xml_node': <object>, 'driver_name': <string>, \
                    'driver_type': <string>, 'source_file': <string>}]
        '''

        dom_disk_infos = []
        for dom_disk_node in dom_disk_nodes:

            # print etree.tostring(dom_disk_node)

            driver_name = None
            driver_type = None
            source_file = None
            try:
                driver_name = dom_disk_node.find('driver').get('name')
                if driver_name is None:
                    raise
                if driver_name not in self.DRIVER_TYPES:
                    sys.stderr.write('\ndomain \'%s\' is using a unknown \
                                      disk driver name \'%s\'. abort.\n\n' \
                                      % (args.dom_name, driver_name))
                    sys.exit(1)
            except all:
                sys.stderr.write('\nfailed to get disk driver name for \
                                domain \'%s\'. abort.\n\n' % (dom_name))
                sys.exit(1)

            try:
                driver_type = dom_disk_node.find('driver').get('type')
                if driver_type is None:
                    raise
                if driver_type not in \
                   self.DRIVER_TYPES[driver_name]['formats']:

                    sys.stderr.write('\ndomain \'%s\' is using a unknown \
                                    disk driver type \'%s\'. abort.\n\n' \
                                    % (args.dom_name, driver_type))
                    sys.exit(1)
            except all:
                sys.stderr.write('\nfailed to get disk driver type for \
                                domain \'%s\'. abort.\n\n' % (dom_name))
                sys.exit(1)

            try:
                source_file = dom_disk_node.find('source').get('file')
                if source_file is None:
                    raise
            except all:
                sys.stderr.write('\nfailed to get disk image file name for \
                                domain \'%s\'. abort.\n\n' % (dom_name))
                sys.exit(1)

            dom_disk_infos.append(
                {
                    'xml_node': dom_disk_node,
                    'driver_name' : driver_name,
                    'driver_type' : driver_type,
                    'source_file' : source_file
                }
            )

        return dom_disk_infos

    def _get_dom_file_disk_info(self, dom_name):

        ''' Extract and return all disk definitions of type file
            for the given domain.

        :param dom_name: name of the domain the information is requested for
        :returns: dom xml node and list of dictionaries root, [{'xml_node':
                  <object>, 'driver_name': <string>, 'driver_type': <string>,
                  'source_file': <string>}]
        '''

        dom = None
        try:
            dom = self._lvirt_conn.lookupByName(dom_name)
        except all:
            sys.stderr.write('\nno domain with name \'%s\' found. \
                              abort.\n\n' % (dom_name))
            sys.exit(1)

        if dom.isActive() == True:
            sys.stderr.write('\ndomain \'%s\' is running - please shutdown \
                              before converting the disk images. \
                              abort.\n\n' % (dom_name))
            sys.exit(1)

        root = None
        try:
            root = etree.fromstring(dom.XMLDesc(0))
            if root is None:
                raise
            # print etree.tostring(root)
        except all:
            sys.stderr.write('\nfailed to get XML domain description for \
                              domain \'%s\'. abort.\n\n' % (dom_name))
            sys.exit(1)

        try:
            dom_disk_nodes = root.xpath('//devices/disk[contains(@type, \
                                         "file")]')
            if len(dom_disk_nodes) == 0:
                raise
        except all:
            sys.stderr.write('\nno disk definitions of type file for \
                              domain \'%s\'. abort.\n\n' % (dom_name))
            sys.exit(1)

        return root, \
               self._get_info_from_dom_disk_nodes(dom_disk_nodes, dom_name)

    def _create_convert_tasks(self, disk_infos, destination_format, \
                             add_type_extension):
        ''' Create a convert task for each disk info.

        :param disk_infos: list of disk definitions
        :param destination_format: string containing the format
        :return: list of task [{disk_info: <object>, destination_format: \
                 <string>}, destination_file: <string>}]
        '''

        convert_tasks = []
        for disk_info in disk_infos:

            if destination_format == disk_info['driver_type']:
                continue

            if destination_format not in \
               self.DRIVER_TYPES[disk_info['driver_name']]['formats']:
                sys.stderr.write('\ntarget format \'%s\' not supported for \
                                  disk using driver \'%s\'. abort.\n\n' \
                                  % (destination_format, \
                                     disk_info['driver_name']))
                sys.exit(1)

            source_uid = None
            source_gid = None
            try:
                source_fd = os.open(disk_info['source_file'], os.O_RDWR)
                info = os.fstat(source_fd)
                source_uid = info.st_uid
                source_gid = info.st_gid
                source_perm = info.st_mode
                os.close(source_fd)

            except IOError as err:
                sys.stderr.write('\nfailed to access file \'%s\'\n \
                                  cause:\n%s\nabort.\n\n' \
                                  % (disk_info['source_file'], err))
                sys.exit(1)

            destination_file = disk_info['source_file']
            if add_type_extension is True:

                destination_file = (os.path.splitext(destination_file)[0]) + \
                                    '.' + self.DRIVER_TYPES[ \
                                    disk_info['driver_name']]['formats'] \
                                    [destination_format]

            convert_tasks.append(
                {
                    'disk_info' : disk_info,
                    'destination_format' : destination_format,
                    'destination_file' : destination_file,
                    'owner_id' : source_uid,
                    'group_id' : source_gid,
                    'permissions' : source_perm,
                    'processed' : False
                }
            )

        return convert_tasks

    def __init__(self, connection_uri, dom_name, destination_format, \
                 add_type_extension = False):

        try:
            self._lvirt_conn = libvirt.open(connection_uri)
        except libvirt.libvirtError as err:
            sys.stderr.write('\nfailed to open connection to the \
                              hyper-visor cause:\n%s\n\n' % (err))
            sys.exit(1)

        self._xml_root, self._disk_infos = \
          self._get_dom_file_disk_info(dom_name)

        # print self._disk_infos

        self._convert_tasks = self._create_convert_tasks(self._disk_infos, \
                                                        destination_format, \
                                                         add_type_extension)

        # print self._convert_tasks

        self._domain = dom_name

    def __del__(self):

        try:
            self._lvirt_conn.close()
        except all:
            pass

    def get_task_num(self):
        ''' Return the number of converter tasks.

        :returns: number of tasks
        '''

        return len(self._convert_tasks)

    def show_task_list(self):
        ''' Output the task list to stdout. '''

        for idx, task in enumerate(self._convert_tasks):
            print '%2d: [%s]:%s -> [%s]:%s' % (idx,
                                            task['disk_info']['driver_type'],
                                            task['disk_info']['source_file'],
                                            task['destination_format'],
                                            task['destination_file'])

    def convert_all(self, show_progress_bar = False, keep_ownership=False, \
                   keep_permissions=False):
        ''' Run all present tasks.

        :param show_progress_bar: if true, show the progress-bar generated \
               by qemu-img convert
        :param keep_ownership: keep the ownership of the source file
        :param keep_permissions: keep the file permissions of the source file
        :return: number of converted files
        '''

        idx = None
        for idx in range(len(self._convert_tasks)):
            self.convert_selected(idx,
                                 show_progress_bar = show_progress_bar,
                                 keep_ownership = keep_ownership,
                                 keep_permissions = keep_permissions)

        return idx

    def _qemu_convert(self, source_file, source_format, destination_file, \
                      destination_format, show_progress_bar):
        ''' Convert image file using qemu-img convert.

        :param source_file: source disk image file
        :param source_format: source disk image format
        :param destination_file: destination disk image format
        :param destination_format: destination disk image format
        :param show_progress_bar: if true, show the progress-bar generated \
               by qemu-img convert
        '''

        stdout_to = subprocess.PIPE
        qemu_cmd = ['qemu-img',
                    'convert',
                    '-f', source_format,
                    '-O', destination_format
                   ]
        if show_progress_bar is True:
            qemu_cmd.append('-p')
            stdout_to = None

        qemu_cmd.append(source_file)
        qemu_cmd.append(destination_file)

        try:
            if show_progress_bar is True:
                print '\nconvert image \'%s\' from format \'%s\' to \'%s\'' \
                       % (source_file, source_format, \
                       destination_format)

            ret = subprocess.call(qemu_cmd, stdout = stdout_to)

            if ret != 0:
                raise
        except all:
            sys.stderr.write('\nfailed to convert \'%s\' from format \'%s\' \
                              to \'%s\'. abort.\n\n' % (source_file, \
                              source_format, destination_format))
            sys.exit(1)

    def convert_selected(self, idx, show_progress_bar = False, \
                        keep_ownership=False, keep_permissions=False):
        ''' Only run task selected by id.

        :param idx: id of the task to be run
        :param show_progress_bar: if true, show the progressbar generated \
               by qemu-img convert
        :param keep_ownership: keep the ownership of the source file
        :param keep_permissions: keep the file permissions of the source file
        '''

        try:
            task = self._convert_tasks[idx]
        except all:
            sys.stderr.write('\ninvalid task id given. abort.\n\n')
            sys.exit(1)

        # print task

        driver_name = task['disk_info']['driver_name']
        source_format = self.DRIVER_TYPES[driver_name]['formats']\
                                         [task['disk_info']['driver_type']]
        source_file = task['disk_info']['source_file']
        destination_format = self.DRIVER_TYPES[driver_name]['formats']\
                                              [task['destination_format']]
        destination_file = task['destination_file']
        xml_node = task['disk_info']['xml_node']

        try:
            ret = subprocess.call(['qemu-img', 'convert', '-h'], \
                                 stdout=subprocess.PIPE, \
                                 stderr=subprocess.PIPE)
            if  ret is not 1:
                raise
        except all:
            sys.stderr.write('\nfailed to run external tool \'qemu-img \
                              convert\'. abort.\n\n')
            sys.exit(1)

        self._qemu_convert(source_file, source_format, destination_file, \
                           destination_format, show_progress_bar)

        xml_node.find('driver').set('type', destination_format)
        xml_node.find('source').set('file', destination_file)

        if keep_ownership == True:
            try:
                os.chown(destination_file, task['owner_id'], \
                         task['group_id'])
            except IOError as err:
                sys.stderr.write('\nfailed to set ownership for file \'%s\' \
                                  cause:\n\'%s\'\nabort.\n\n' \
                                  % (destination_file, err))
                sys.exit(1)

        if keep_permissions == True:
            try:
                os.chmod(destination_file, task['permissions'])
            except IOError as err:
                sys.stderr.write('\nfailed to set permissions for file \
                                  \'%s\' cause:\n\'%s\'\nabort.\n\n' \
                                  % (destination_file, err))
                sys.exit(1)

        task['processed'] = True

        # print etree.tostring( task['disk_info']['xml_node'])

    def commit_changes(self, remove_old_files = False):
        ''' Update the machine configuration and delete old files if \
            requested.

        :param remove_old_files: if True, old files are deleted
        '''

        self._lvirt_conn.defineXML(etree.tostring(self._xml_root))

        if remove_old_files == True:
            for task in self._convert_tasks:
                if task['processed'] == True:
                    os.remove (task['disk_info']['source_file'])

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--libvirt-connection-uri', \
                   default='qemu:///system', help='URI to connectd to \
                   (default: /etc/libvirt)')
    parser.add_argument('-f', '--output-format', default='qcow2', help='target \
                   format (default: qcow2)')
    parser.add_argument('-n', '--dom-name', required=True, help='name of the \
                   domain the disks should be converted for')
    parser.add_argument('-x', '--add-type-extension', action='store_true', \
                   default=False, help='add type of the image as file \
                   extension to the image file name (default: false)')
    parser.add_argument('-p', '--show-progress-bar', action='store_true', \
                   default=False, help='show progress bar while convert is \
                   running (default: false) ')
    parser.add_argument('-r', '--remove-old-files', action='store_true', \
                   default=False, help='remove old files after all \
                   translations succeeded (default: false)')
    parser.add_argument('-o', '--keep-file-ownership', action='store_true', \
                   default=False, help='keep owner and group of the file \
                   (default: false)')
    parser.add_argument('-k', '--keep-file-permissions', action='store_true', \
                   default=False, help='apply file permissions of the \
                   source file (default: false)')

    args = parser.parse_args()

    converter = LibVirtDriveConvert(args.libvirt_connection_uri, \
                                    args.dom_name, \
                                    args.output_format, \
                                    add_type_extension = \
                                                  args.add_type_extension)

    converter.show_task_list()

    converter.convert_all(show_progress_bar = args.show_progress_bar, \
                          keep_ownership = args.keep_file_ownership, \
                          keep_permissions = args.keep_file_permissions)

    converter.commit_changes(remove_old_files = args.remove_old_files)


text:
TemplateController('counterButton', {

  props: new SimpleSchema({
    label: { type: String },
    value: { type: String },
    count: { type: Function },
    isActive: { type: Function },
    onClicked: { type: Function },
    buttonId: {
      type: String,
      optional: true
    }
  }),

  helpers: {
    activeClass() {
      return this.props.isActive(this.props.value) ? 'active' : null;
    },
    count() {
      return this.props.count(this.props.value);
    }
  },

  events: {
    'click button'() {
      this.props.onClicked(this.props.value);
    }
  }

});