text:
((Ext.isIE9m || Ext.isFirefox) ? xdescribe : describe)("Ext.event.gesture.DoubleTap", function() {
    var helper = Ext.testHelper,
        recognizer = Ext.event.gesture.DoubleTap.instance,
        moveDistance = recognizer.getMoveDistance(),
        tapDistance = recognizer.getTapDistance(),
        maxDuration = 130,
        offset = 60,
        originalMaxDuration, targetEl, singleTapHandler, doubleTapHandler, e;

    function start(cfg) {
        helper.touchStart(targetEl, cfg);
    }

    function move(cfg) {
        helper.touchMove(targetEl, cfg);
    }

    function end(cfg) {
        helper.touchEnd(targetEl, cfg);
    }

    function cancel(cfg) {
        helper.touchCancel(targetEl, cfg);
    }

    beforeEach(function() {
        originalMaxDuration = recognizer.getMaxDuration();
        recognizer.setMaxDuration(maxDuration);
        targetEl = Ext.getBody().createChild({});
        singleTapHandler = jasmine.createSpy();
        doubleTapHandler = jasmine.createSpy();

        singleTapHandler.andCallFake(function(event) {
            e = event;
        });

        doubleTapHandler.andCallFake(function(event) {
            e = event;
        });

        targetEl.on('doubletap', doubleTapHandler);
        targetEl.on('singletap', singleTapHandler);
    });

    afterEach(function() {
        recognizer.setMaxDuration(originalMaxDuration);
        targetEl.destroy();
    });

    it("should fire doubletap and not singletap when a second tap occurs within maxDuration", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waits(maxDuration - offset);
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).toHaveBeenCalled();
            expect(singleTapHandler).not.toHaveBeenCalled();
            expect(e && e.type).toBe('doubletap');
        });
    });

    it("should fire singletap and not doubletap when a second tap does not occur within maxDuration", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waits(maxDuration + 30);
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).not.toHaveBeenCalled();
            expect(singleTapHandler).toHaveBeenCalled();
            expect(e && e.type).toBe('singletap');
        });
    });

    it("should not fire singletap if movement of the first pointer exceeds moveDistance", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            move({ id: 1, x: 10, y: 10 + moveDistance });
            end({ id: 1, x: 10, y: 10 + moveDistance });
        });
        waits(maxDuration + 30);
        runs(function() {
            expect(singleTapHandler).not.toHaveBeenCalled();
        });
    });

    it("should not fire doubletap if movement of the first pointer exceeds moveDistance", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            move({ id: 1, x: 10, y: 10 + moveDistance });
            end({ id: 1, x: 10, y: 10 + moveDistance });
        });
        waits(maxDuration - offset);
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).not.toHaveBeenCalled();
        });
        waits(maxDuration + 30);
        runs(function() {
            // The second tap should actually trigger the single tap event
            expect(singleTapHandler).toHaveBeenCalled();
        })
    });

    it("should fire singletap if movement of the first pointer is within moveDistance", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            move({ id: 1, x: 10, y: 9 + moveDistance });
            end({ id: 1, x: 10, y: 9 + moveDistance });
        });
        waits(maxDuration + 30);
        runs(function() {
            expect(singleTapHandler).toHaveBeenCalled();
        });
    });

    it("should fire doubletap if movement of the first pointer is within moveDistance", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            move({ id: 1, x: 9 + moveDistance, y: 10 });
            end({ id: 1, x: 9 + moveDistance, y: 10 });
        });
        waits(maxDuration - offset);
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 11, y: 11 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).toHaveBeenCalled();
        });
    });

    it("should fire a doubletap if done after a touchend is vetoed", function() {
        targetEl.on('touchend', function(e) {
            e.stopEvent();
        }, null, {single: true});

        runs(function() {
            start({ id: 1, x: 400, y: 10 });
            end({ id: 1, x: 400, y: 10 });
        });
        waits(maxDuration + 100);
        runs(function() {
            expect(doubleTapHandler).not.toHaveBeenCalled();
            start({ id: 2, x: 10, y: 10 });
            end({ id: 2, x: 10, y: 10 });
        });
        waits(maxDuration - 60);
        runs(function() {
            expect(doubleTapHandler).not.toHaveBeenCalled();
            start({ id: 3, x: 10, y: 10 });
            end({ id: 3, x: 10, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).toHaveBeenCalled();
        });
    });

    it("should fire double tap if the second tap is within tapDistance from the first tap", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waits(maxDuration - offset);
        runs(function() {
            start({ id: 1, x: 10 + tapDistance, y: 10 });
            end({ id: 1, x: 10 + tapDistance, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).toHaveBeenCalled();
        });
    });

    it("should not fire double tap if the second tap exceeds tapDistance from the first tap", function() {
        runs(function() {
            start({ id: 1, x: 10, y: 10 });
            end({ id: 1, x: 10, y: 10 });
        });
        waits(maxDuration - offset);
        runs(function() {
            start({ id: 1, x: 11 + tapDistance, y: 10 });
            end({ id: 1, x: 11 + tapDistance, y: 10 });
        });
        waitsForAnimation();
        runs(function() {
            expect(doubleTapHandler).not.toHaveBeenCalled();
        });
    });

    if (Ext.supports.Touch) {
        it("should not fire single tap if the first touch is canceled", function() {
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                cancel({ id: 1, x: 10, y: 10 });
            });
            waits(maxDuration + 30);
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                end({ id: 1, x: 10, y: 10 });
            });
            waitsForAnimation();
            runs(function() {
                expect(singleTapHandler).not.toHaveBeenCalled();
            });
        });

        it("should not fire double tap if the first touch is canceled", function() {
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                cancel({ id: 1, x: 10, y: 10 });
            });
            waits(maxDuration - offset);
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                end({ id: 1, x: 10, y: 10 });
            });
            waitsForAnimation();
            runs(function() {
                expect(doubleTapHandler).not.toHaveBeenCalled();
            });
        });

        it("should not fire double tap if the second touch is canceled", function() {
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                end({ id: 1, x: 10, y: 10 });
            });
            waits(maxDuration - offset);
            runs(function() {
                start({ id: 1, x: 10, y: 10 });
                cancel({ id: 1, x: 10, y: 10 });
            });
            waitsForAnimation();
            runs(function() {
                expect(doubleTapHandler).not.toHaveBeenCalled();
            });
        });
    }
});


text:
package org.cometd.client.http;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Promise;
import org.cometd.bayeux.client.ClientSession;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.server.LocalSession;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.client.BayeuxClient;
import org.cometd.client.http.jetty.JettyHttpClientTransport;
import org.cometd.client.transport.ClientTransport;
import org.cometd.common.JSONContext;
import org.cometd.common.JettyJSONContextClient;
import org.cometd.server.AbstractServerTransport;
import org.cometd.server.JettyJSONContextServer;
import org.eclipse.jetty.util.ajax.JSON;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class JettyCustomSerializationTest extends ClientServerTest {
    @Test
    public void testJettyCustomSerialization() throws Exception {
        Map<String, String> serverOptions = new HashMap<>();
        serverOptions.put(AbstractServerTransport.JSON_CONTEXT_OPTION, TestJettyJSONContextServer.class.getName());
        Map<String, Object> clientOptions = new HashMap<>();
        clientOptions.put(ClientTransport.JSON_CONTEXT_OPTION, new TestJettyJSONContextClient());

        start(serverOptions);

        String broadcastChannelName = "/data";
        String serviceChannelName = "/service/data";
        String content = "random";
        CountDownLatch broadcastLatch = new CountDownLatch(1);
        CountDownLatch serviceLatch = new CountDownLatch(2);

        LocalSession service = bayeux.newLocalSession("custom_serialization");
        service.handshake();
        service.getChannel(broadcastChannelName).subscribe((channel, message) -> {
            Data data = (Data)message.getData();
            Assertions.assertEquals(content, data.content);
            Map<String, Object> ext = message.getExt();
            Assertions.assertNotNull(ext);
            Extra extra = (Extra)ext.get("extra");
            Assertions.assertEquals(content, extra.content);
            broadcastLatch.countDown();
        });

        bayeux.createChannelIfAbsent(serviceChannelName).getReference().addListener(new ServerChannel.MessageListener() {
            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                Data data = (Data)message.getData();
                Assertions.assertEquals(content, data.content);
                Map<String, Object> ext = message.getExt();
                Assertions.assertNotNull(ext);
                Extra extra = (Extra)ext.get("extra");
                Assertions.assertEquals(content, extra.content);
                serviceLatch.countDown();

                ServerMessage.Mutable mutable = bayeux.newMessage();
                mutable.setChannel(serviceChannelName);
                mutable.setData(new Data(content));
                mutable.getExt(true).put("extra", new Extra(content));
                from.deliver(service, message, Promise.noop());

                return true;
            }
        });

        BayeuxClient client = new BayeuxClient(cometdURL, new JettyHttpClientTransport(clientOptions, httpClient));
        client.addExtension(new ExtraExtension(content));
        client.getChannel(serviceChannelName).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (!message.isPublishReply()) {
                Data data = (Data)message.getData();
                Assertions.assertEquals(content, data.content);
                Map<String, Object> ext = message.getExt();
                Assertions.assertNotNull(ext);
                Extra extra = (Extra)ext.get("extra");
                Assertions.assertEquals(content, extra.content);
                serviceLatch.countDown();
            }
        });

        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        // Wait for the /meta/connect.
        Thread.sleep(1000);

        client.getChannel(broadcastChannelName).publish(new Data(content));
        client.getChannel(serviceChannelName).publish(new Data(content));
        Assertions.assertTrue(broadcastLatch.await(5, TimeUnit.SECONDS));
        Assertions.assertTrue(serviceLatch.await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @Test
    public void testParserGenerator() throws Exception {
        JSONContext.Client jsonContext = new TestJettyJSONContextClient();
        Data data1 = new Data("data");
        Extra extra1 = new Extra("extra");
        Map<String, Object> map1 = new HashMap<>();
        map1.put("data", data1);
        map1.put("extra", extra1);
        String json = jsonContext.getGenerator().generate(map1);
        @SuppressWarnings("unchecked")
        Map<String, Object> map2 = jsonContext.getParser().parse(new StringReader(json), Map.class);
        Data data2 = (Data)map2.get("data");
        Extra extra2 = (Extra)map2.get("extra");
        Assertions.assertEquals(data1.content, data2.content);
        Assertions.assertEquals(extra1.content, extra2.content);
    }

    private static class ExtraExtension implements ClientSession.Extension {
        private final String content;

        public ExtraExtension(String content) {
            this.content = content;
        }

        @Override
        public boolean send(ClientSession session, Message.Mutable message) {
            Map<String, Object> ext = message.getExt(true);
            ext.put("extra", new Extra(content));
            return true;
        }
    }

    private static class TestJettyJSONContextClient extends JettyJSONContextClient {
        private TestJettyJSONContextClient() {
            getJSON().addConvertor(Data.class, new DataConvertor());
            getJSON().addConvertor(Extra.class, new ExtraConvertor());
        }
    }

    public static class TestJettyJSONContextServer extends JettyJSONContextServer {
        public TestJettyJSONContextServer() {
            putConvertor(Data.class.getName(), new DataConvertor());
            putConvertor(Extra.class.getName(), new ExtraConvertor());
        }
    }

    private static class Data {
        private final String content;

        private Data(String content) {
            this.content = content;
        }
    }

    private static class Extra {
        private final String content;

        private Extra(String content) {
            this.content = content;
        }
    }

    private static class DataConvertor implements JSON.Convertor {
        @Override
        public void toJSON(Object object, JSON.Output output) {
            Data data = (Data)object;
            output.addClass(Data.class);
            output.add("content", data.content);
        }

        @Override
        public Object fromJSON(Map<String, Object> map) {
            String content = (String)map.get("content");
            return new Data(content);
        }
    }

    private static class ExtraConvertor implements JSON.Convertor {
        @Override
        public void toJSON(Object object, JSON.Output output) {
            Extra extra = (Extra)object;
            output.addClass(Extra.class);
            output.add("content", extra.content);
        }

        @Override
        public Object fromJSON(Map<String, Object> map) {
            String content = (String)map.get("content");
            return new Extra(content);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['angular','../const/constants'], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = function (root, angular) {
            if (angular === undefined) {
                if (typeof window !== 'undefined') {
                    angular = require('angular');

                } else {
                    angular = require('angular')(root);
                }
            }
            factory(angular, require('../const/constants'));
            return angular;
        };
    } else {
        factory(angular);
    }
}(function (angular) {

    'use strict';

    var AlertController = function(keyCodeConst, $attrs) {
        var ctrl = this;
        ctrl.closeable = !!$attrs.close;
        ctrl.typeSpecified = !!$attrs.type;

        ctrl.handleKeypress = function (evt) {
            if (evt.keyCode === keyCodeConst.SPACE) {
                evt.preventDefault();
                ctrl.close();
            }
        };
    };
    AlertController.$inject = ['WF-KEYCODE-CONST','$attrs'];

    angular.module('wf.angular.alerts',['wf.angular.constants'])
        .component('wfAlert', {
            transclude: true,
            templateUrl: 'wf/ng-template/alerts/alerts.html',
            bindings: {
                type: '@',
                close: '&'
            },
            controller: AlertController
        });
    }
));


text:
package com.morgan.server.polymer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

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

import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.io.ByteSource;
import com.google.common.io.Resources;
import com.google.common.net.MediaType;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.morgan.server.util.log.AdvancedLogger;
import com.morgan.server.util.log.InjectLogger;
import com.morgan.server.util.mime.MediaTypeMapper;
import com.morgan.server.util.stat.MeasureStatistics;

/**
 * Servlet for serving the polymer components (located under the accompanying resources folder).
 *
 * @author mark@mark-morgan.net (Mark Morgan)
 */
@Singleton
class PolymerComponentServlet extends HttpServlet {

  static final long serialVersionUID = 1L;

  private static final CharMatcher LEADING_SLASH_TRIMMER = CharMatcher.is('/');

  @InjectLogger AdvancedLogger log = AdvancedLogger.NULL;

  private final Function<String, MediaType> contentTypeMapper;

  @Inject PolymerComponentServlet(@MediaTypeMapper Function<String, MediaType> contentTypeMapper) {
    this.contentTypeMapper = contentTypeMapper;
  }

  private static String getFileNameForPath(String path) {
    int i = path.lastIndexOf('/');
    if (i >= 0) {
      return path.substring(i + 1);
    }

    return path;
  }

  @MeasureStatistics
  @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String relativePath = LEADING_SLASH_TRIMMER.trimLeadingFrom(req.getPathInfo());

    URL resourceUrl = Resources.getResource(
        PolymerComponentServlet.class, "resources/" + relativePath);
    ByteSource source = Resources.asByteSource(resourceUrl);

    log.debug("Attempting to get content type of path %s", relativePath);
    MediaType contentType = contentTypeMapper.apply(getFileNameForPath(relativePath));
    log.debug("Got back a content type of %s", contentType);
    try (OutputStream out = resp.getOutputStream()) {
      resp.setContentType(contentType.toString());

      source.copyTo(out);
    }
  }
}


text:
					{{node.name}}

				 Add


text:
using Microsoft.Xna.Framework.Graphics;
using StryfeRPG.Managers.Data;
using StryfeRPG.Models.Characters;
using StryfeRPG.Models.Items;
using StryfeRPG.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using StryfeRPG.System.Windows;
using StryfeRPG.Managers.GUI;
using StryfeCore.Models.Utils;

namespace StryfeRPG.Managers
{
    public class CharacterManager : WindowManager
    {
        private AttributeSheet Attributes;
        private Texture2D slotTexture;
        private int selectedAtt;

        public void AddExperience(int experience)
        {
            int oldLevel = Attributes.PureBase[CharacterAttribute.Level];

            Attributes.PureBase[CharacterAttribute.Experience] += experience;
            Attributes.Recalculate();

            QuickMessageManager.Instance.ShowMessage(new QuickMessage("Experience gained", string.Format("+{0}XP", experience)));

            int currentLevel = Attributes.PureBase[CharacterAttribute.Level];
            if (currentLevel > oldLevel)
                QuickMessageManager.Instance.ShowMessage(new QuickMessage("Level gained", string.Format("You're now level {0}!", currentLevel)));
        }

        public void AddModifier(AttributeModifier modifier)
        {
            AttributeSheet sheet = Global.Player.Attributes;
            switch (modifier.Type)
            {
                case ModifierType.Current:
                    int att = sheet.Current[modifier.Attribute] + modifier.Value;
                    if (att > sheet.Calculated[modifier.Attribute])
                        att = sheet.Calculated[modifier.Attribute];
                    else if (att < 0)
                        att = 0;
                    sheet.Current[modifier.Attribute] = att;
                    break;

                case ModifierType.Permanent:
                case ModifierType.Temporary:
                case ModifierType.Equipment:
                    sheet.Modifiers.Add(modifier);
                    break;
            }

            sheet.Recalculate();
        }

        public void RemoveModifiers(int itemId)
        {
            AttributeSheet sheet = Global.Player.Attributes;
            AttributeModifier mod = null;
            foreach (AttributeModifier att in sheet.Modifiers)
            {
                if (att.ItemId == itemId)
                {
                    mod = att;
                    break;
                }
            }

            if (mod != null)
            {
                sheet.Modifiers.Remove(mod);
                sheet.Recalculate();
            }
        }

        public override void Draw(SpriteBatch spriteBatch, double timePassed)
        {
            if (!IsOpened)
                return;

            WindowUtils.spriteBatch = spriteBatch;

            // Window
            Window window = new Window(bounds.Center.X - Width / 2, bounds.Center.Y - Height / 2, Width, Height);
            window.Margin = 20;

            // Attributes
            SpriteFont font = Global.DetailFont;
            int fontHeight = font.LineSpacing / 2;
            int innerMargin = 5;
            Vector2 maxSize = new Vector2(115, 50);
            int biggerX = (int)font.MeasureString("Intelligence:").X / 2;

            window.AddChild(new TextWindow(font, "Level:", new Vector2(biggerX - font.MeasureString("Level:").X / 2, 0), maxSize, Color.Cyan));

            window.AddChild(new TextWindow(font, "Vitality:", new Vector2(biggerX - font.MeasureString("Vitality:").X / 2, fontHeight + innerMargin), maxSize));
            window.AddChild(new TextWindow(font, "Wisdom:", new Vector2(biggerX - font.MeasureString("Wisdom:").X / 2, (fontHeight + innerMargin) * 2), maxSize));
            window.AddChild(new TextWindow(font, "Endurance:", new Vector2(biggerX - font.MeasureString("Endurance:").X / 2, (fontHeight + innerMargin) * 3), maxSize));
            window.AddChild(new TextWindow(font, "Strenght:", new Vector2(biggerX - font.MeasureString("Strenght:").X / 2, (fontHeight + innerMargin) * 4), maxSize));
            window.AddChild(new TextWindow(font, "Dexterity:", new Vector2(biggerX - font.MeasureString("Dexterity:").X / 2, (fontHeight + innerMargin) * 5), maxSize));
            window.AddChild(new TextWindow(font, "Intelligence:", new Vector2(0, (fontHeight + innerMargin) * 6), maxSize));
            window.AddChild(new TextWindow(font, "Faith:", new Vector2(biggerX - font.MeasureString("Faith:").X / 2, (fontHeight + innerMargin) * 7), maxSize));
            window.AddChild(new TextWindow(font, "Luck:", new Vector2(biggerX - font.MeasureString("Luck:").X / 2, (fontHeight + innerMargin) * 8), maxSize));

            window.AddChild(new TextWindow(font, "Points left:", new Vector2(biggerX - font.MeasureString("Points left:").X / 2, (fontHeight + innerMargin) * 9), maxSize, Color.Cyan));
            window.AddChild(new TextWindow(font, "Experience:", new Vector2(biggerX - font.MeasureString("Experience:").X / 2, (fontHeight + innerMargin) * 10), maxSize, Color.Cyan));

            // Values
            int x = biggerX + innerMargin;
            Dictionary<CharacterAttribute, int> atts = Attributes.PureBase;

            window.AddChild(new TextWindow(font, Attributes.PureBase[CharacterAttribute.Level].ToString(), new Vector2(x, 0), maxSize, Color.Cyan));

            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Vitality].ToString(), new Vector2(x, (fontHeight + innerMargin)), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Wisdom].ToString(), new Vector2(x, (fontHeight + innerMargin) * 2), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Endurance].ToString(), new Vector2(x, (fontHeight + innerMargin) * 3), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Strenght].ToString(), new Vector2(x, (fontHeight + innerMargin) * 4), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Dexterity].ToString(), new Vector2(x, (fontHeight + innerMargin) * 5), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Intelligence].ToString(), new Vector2(x, (fontHeight + innerMargin) * 6), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Faith].ToString(), new Vector2(x, (fontHeight + innerMargin) * 7), maxSize, Color.Yellow));
            window.AddChild(new TextWindow(font, atts[CharacterAttribute.Luck].ToString(), new Vector2(x, (fontHeight + innerMargin) * 8), maxSize, Color.Yellow));

            window.AddChild(new TextWindow(font, Attributes.PointsLeft.ToString(), new Vector2(x, (fontHeight + innerMargin) * 9), maxSize, Color.Cyan));
            window.AddChild(new TextWindow(font, Attributes.PureBase[CharacterAttribute.Experience].ToString(), new Vector2(x, (fontHeight + innerMargin) * 10), maxSize, Color.Cyan));

            // Buttons
            x += 100;
            int buttonSize = fontHeight * 2;
            innerMargin = 10;
            window.AddChild(new Window(x, (buttonSize + innerMargin), buttonSize, buttonSize, slotTexture, selectedAtt == 0 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 2, buttonSize, buttonSize, slotTexture, selectedAtt == 1 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 3, buttonSize, buttonSize, slotTexture, selectedAtt == 2 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 4, buttonSize, buttonSize, slotTexture, selectedAtt == 3 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 5, buttonSize, buttonSize, slotTexture, selectedAtt == 4 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 6, buttonSize, buttonSize, slotTexture, selectedAtt == 5 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 7, buttonSize, buttonSize, slotTexture, selectedAtt == 6 ? Color.Cyan : Color.White));
            window.AddChild(new Window(x, (buttonSize + innerMargin) * 8, buttonSize, buttonSize, slotTexture, selectedAtt == 7 ? Color.Cyan : Color.White));

            WindowUtils.DrawWindow(window);
        }

        public override void PerformAction()
        {
            if (Global.Player.Attributes.PointsLeft == 0)
                return;

            CharacterAttribute att = CharacterAttribute.Vitality;
            switch (selectedAtt)
            {
                case 0:
                    att = CharacterAttribute.Vitality;
                    break;
                case 1:
                    att = CharacterAttribute.Wisdom;
                    break;
                case 2:
                    att = CharacterAttribute.Endurance;
                    break;
                case 3:
                    att = CharacterAttribute.Strenght;
                    break;
                case 4:
                    att = CharacterAttribute.Dexterity;
                    break;
                case 5:
                    att = CharacterAttribute.Intelligence;
                    break;
                case 6:
                    att = CharacterAttribute.Faith;
                    break;
                case 7:
                    att = CharacterAttribute.Luck;
                    break;
            }

            Attributes.PureBase[att]++;
            Attributes.PointsLeft--;
            Attributes.Recalculate();
        }

        public override void Move(Vector2 movement)
        {
            selectedAtt += (int)movement.Y;
            if (selectedAtt < 0)
                selectedAtt = 0;
            else if (selectedAtt > 7)
                selectedAtt = 7;
        }

        // Singleton stuff
        private static CharacterManager instance;
        protected CharacterManager()
        {
            slotTexture = Global.GetTexture("item_bg");
            selectedAtt = 0;

            Width = 250;
            Height = 400;

            Attributes = Global.Player.Attributes;
        }
        public static CharacterManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CharacterManager();
                }
                return instance;
            }
        }
    }
}


text:
require "erb"
include ERB::Util

class RulesController < ApplicationController

  SECTION=Navigation::SECTION_CONFIGURATION

  # GET /rules/show/<key>
  # This URL is used by the Eclipse plugin
  #
  # Example: GET /rules/show/squid:AvoidCycles
  #
  def show
    require_parameters :id

    # the redirect is needed for the backward compatibility with eclipse plugin
    url = url_for :controller => 'coding_rules', :action => 'index'
    url = url + '#rule_key=' + url_encode(params[:id])
    redirect_to url
  end
end


text:
create table One
(
	Id int not null identity(1,1),

	constraint PK_One primary key clustered (Id),
)
GO

create table Two
(
	Id int not null identity(1,1),

	constraint PK_Two primary key clustered (Id),
)
GO


text:
/**
 * write str to a file.If the dir is not exist,create it
 */
'use strict';

const write = require('write');

/**
 * @param {String} outputPath - file path
 * @param {String} str - str which will be wrote into file
 * @param {Function} callback - callback function
 */
module.exports = (outputPath, str, callback) => {
    // if there is problem, try other way to achieve it.
    write(outputPath, str, callback);
};


text:
#include <glog/logging.h>
#include <folly/experimental/ThreadedRepeatingFunctionRunner.h>
#include <folly/init/Init.h>
#include <folly/ScopeGuard.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>

#include "bistro/bistro/Bistro.h"
#include "bistro/bistro/config/FileConfigLoader.h"
#include "bistro/bistro/monitor/Monitor.h"
#include "bistro/bistro/nodes/NodesLoader.h"
#include "bistro/bistro/runners/NoOpRunner.h"
#include "bistro/bistro/runners/BenchmarkRunner.h"
#include "bistro/bistro/runners/LocalRunner.h"
#include "bistro/bistro/runners/RemoteWorkerRunner.h"
#include "bistro/bistro/scheduler/SchedulerPolicies.h"
#include "bistro/bistro/server/HTTPMonitorServer.h"
#include "bistro/bistro/server/ThriftMonitor.h"
#include "bistro/bistro/statuses/SQLiteTaskStore.h"
#include "bistro/bistro/statuses/TaskStatuses.h"

DECLARE_int32(server_port); // from server_socket.cpp

DEFINE_string(config_file, "", "File to use for resource and job config");
DEFINE_int32(config_update_ms, 10000, "How often to re-read the config");
DEFINE_int32(nodes_update_ms, 300000, "How often to re-read the nodes");
DEFINE_int32(
  nodes_retry_ms, 30000,
  "How often to re-try reading the nodes after failures"
);
DEFINE_bool(clean_statuses, false, "If true, don't read/write statuses");
DEFINE_string(status_table, "", "Name of DB table that stores statuses.");
DEFINE_bool(
  dry_run,
  false,
  "If true, don't actually run any tasks. Also implies clean_statuses"
);
DEFINE_bool(
  benchmark_run,
  false,
  "Runs sleep tasks with configurable duration and failure, Also implies"
  "clean_statuses"
);
DEFINE_string(worker_command, "", "If set, use local task mode");
DEFINE_string(data_dir, "/data/bistro", "Data for local tasks is stored here");

using namespace std;
using namespace facebook::bistro;

int main(int argc, char* argv[]) {
  FLAGS_logtostderr = 1;
  folly::init(&argc, &argv);

  registerDefaultSchedulerPolicies();

  boost::filesystem::path config_file(FLAGS_config_file);
  auto config_loader = make_shared<FileConfigLoader>(
    std::chrono::milliseconds(FLAGS_config_update_ms),
    boost::filesystem::absolute(config_file)
  );
  auto nodes_loader = make_shared<NodesLoader>(
    config_loader,
    std::chrono::milliseconds(FLAGS_nodes_update_ms),
    std::chrono::milliseconds(FLAGS_nodes_retry_ms)
  );

  shared_ptr<TaskStore> task_store;
  if (FLAGS_clean_statuses || FLAGS_dry_run || FLAGS_benchmark_run) {
    task_store.reset(new NoOpTaskStore());
  } else {
    CHECK(!FLAGS_status_table.empty()) << "You must pass --status_table";
    task_store.reset(new SQLiteTaskStore(FLAGS_data_dir, FLAGS_status_table));
  }

  auto task_statuses = make_shared<TaskStatuses>(task_store);

  auto monitor = make_shared<Monitor>(
    config_loader,
    nodes_loader,
    task_statuses
  );

  shared_ptr<TaskRunner> task_runner;
  if (FLAGS_dry_run) {
    task_runner.reset(new NoOpRunner());
  } else if (FLAGS_benchmark_run) {
    task_runner.reset(new BenchmarkRunner());
  } else if (!FLAGS_worker_command.empty()) {
    task_runner.reset(new LocalRunner(FLAGS_worker_command, FLAGS_data_dir));
  } else {
    task_runner.reset(new RemoteWorkerRunner(task_statuses, monitor));
  }

  // Initialize the scheduler thread itself
  Bistro bistro(
    config_loader,
    nodes_loader,
    task_statuses,
    task_runner,
    monitor
  );
  folly::ThreadedRepeatingFunctionRunner bistro_thread;
  bistro_thread.add(
    "BistroSchedule", bind(&Bistro::scheduleOnceSystemTime, &bistro)
  );
  SCOPE_EXIT { bistro_thread.stop(); };

  auto http_monitor = make_shared<HTTPMonitor>(
    config_loader,
    nodes_loader,
    task_statuses,
    task_runner,
    monitor
  );

  HTTPMonitorServer http_monitor_server(http_monitor);

  // Initialize the thrift monitor
  auto handler = std::make_unique<ThriftMonitor>(
    config_loader,
    nodes_loader,
    task_statuses,
    task_runner,
    monitor
  );

  auto server = make_shared<apache::thrift::ThriftServer>();
  server->setPort(FLAGS_server_port);
  server->setInterface(std::move(handler));
  server->serve();
}


text:
version: 1.0.0
title: Protocols
---

Nesta lição nós iremos aprender um pouco sobre Protocols, o que eles são e como usamos ele em Elixir.

{% include toc.html %}

## O que são Protocols
Então, o que eles são?
Protocolos são um meio de alcançar polimorfismo no Elixir.
Uma dor de Erlang é estender uma API existente para tipos recentemente definidos.
Para evitar isso no Elixir, a função é despachada dinamicamente com base no tipo do valor.
O Elixir vem com um número de protocolos incorporados, por exemplo, o protocolo `String.Chars` é responsável pela função` to_string / 1` que vimos ser usada anteriormente.
Vamos dar uma analizar `to_string/1` com um exemplo rápido:

```elixir
iex> to_string(5)
"5"
iex> to_string(12.4)
"12.4"
iex> to_string("foo")
"foo"
```

Como você pode ver, chamamos a função em vários tipos e isso demonstrou que funciona com todos eles.
E se chamarmos `to_string/1` em tuplas (ou qualquer tipo que não tenha implementado `String.Chars`)?
Vejamos o exemplo:

```elixir
to_string({:foo})
** (Protocol.UndefinedError) protocol String.Chars not implemented for {:foo}
    (elixir) lib/string/chars.ex:3: String.Chars.impl_for!/1
    (elixir) lib/string/chars.ex:17: String.Chars.to_string/1
```

Como você pode ver, temos um erro de protocol, pois não há nenhuma implementação para tuplas.
Na próxima seção vamos implementar o protocolo `String.Chars` para tuplas.

## Implementando um protocol

Vimos que `to_string/1` ainda não foi implementado para tuplas, então vamos adicioná-lo.
Para criar uma implementação, usaremos `defimpl` com o nosso protocolo e forneceremos a opção `:for` e o nosso tipo.
Vamos dar uma olhada em como ele pode parecer:

```elixir
defimpl String.Chars, for: Tuple do
  def to_string(tuple) do
    interior =
      tuple
      |> Tuple.to_list
      |> Enum.map(&Kernel.to_string/1)
      |> Enum.join(", ")

    "{#{interior}}"
  end
end
```

Se copiarmos isso para o IEx, seremos capazes de chamar `to_string/1` em uma tupla sem obter um erro:

```elixir
iex> to_string({3.14, "apple", :pie})
"{3.14, apple, pie}"
```

Sabemos como implementar um protocolo, mas como podemos definir um novo?
Para o nosso exemplo, implementaremos `to_atom/1`.
Vamos ver como fazer isso com `defprotocol`:

```elixir
defprotocol AsAtom do
  def to_atom(data)
end

defimpl AsAtom, for: Atom do
  def to_atom(atom), do: atom
end

defimpl AsAtom, for: BitString do
  defdelegate to_atom(string), to: String
end

defimpl AsAtom, for: List do
  defdelegate to_atom(list), to: List
end

defimpl AsAtom, for: Map do
  def to_atom(map), do: List.first(Map.keys(map))
end
```

Aqui definimos o nosso protocolo e a função esperado, `to_atom/1`, juntamente com implementações para alguns tipos.
Agora que temos o nosso protocolo, vamos colocá-lo para usar em IEx:

```elixir
iex> import AsAtom
AsAtom
iex> to_atom("string")
:string
iex> to_atom(:an_atom)
:an_atom
iex> to_atom([1, 2])
:"\x01\x02"
iex> to_atom(%{foo: "bar"})
:foo
```

É irrelevante se embora embaixo dos panos structs sejam Maps, mas não compartilhem implementações de protocolo com Maps. Eles não são enumeráveis, não podem ser acessados.

Como podemos ver, os protocolos são uma maneira poderosa de alcançar o polimorfismo.


text:
using System.Windows.Forms;

namespace AudioAdventurer.GameDesigner.Forms
{
    public class BaseEditForm<T> : Form where T:new()
    {
        protected T m_Item;
        protected bool New { get; private set; }
        public T Item { get { return m_Item; } }

        public BaseEditForm()
        {

        }

        public BaseEditForm(T _item)
        {
            m_Item = _item;

            if (m_Item == null)
            {
                m_Item = new T();
                New = true;
            }
        }

        protected virtual string ValidateForm() { return null; }
        protected virtual void SetFormToObject(T _object) { }
        protected virtual void SetObjectToForm(T _object) { }

    }
}


text:
<?php

/*
Widget Name: Business Card Widget
Description: Business Card Widget
Author: Colin Williams
*/

class Business_Card_Widget extends SiteOrigin_Widget {

  function __construct() {
    //Here you can do any preparation required before calling the parent constructor, such as including additional files or initializing variables.

    //Call the parent constructor with the required arguments.
    parent::__construct(
      // The unique id for your widget.
      'business-card-widget',

      // The name of the widget for display purposes.
      __('Business Card Widget', 'sage'),

      // The $widget_options array, which is passed through to WP_Widget.
      // It has a couple of extras like the optional help URL, which should link to your sites help or support page.
      array(
          'description' => __('An Opus Energy Widget', 'sage'),
          'panels_groups' => array('opus'),
      ),

      //The $control_options array, which is passed through to WP_Widget
      array(
      ),

      //The $form_options array, which describes the form fields used to configure SiteOrigin widgets. We'll explain these in more detail later.
      array(
        'header_section' => array(
        'type' => 'section',
        'label' => __( 'Business Card Header' , 'asge' ),
        'hide' => false,
        'fields' => array(
          'icon_selection' => array(
            'type' => 'select',
            'prompt' => __( 'Choose an icon', 'sage' ),
            'options' => array(
                'icon-shop' => __( 'Shop Icon', 'sage' ),
                'icon-question-mark' => __( 'Question Mark', 'sage' ),
                'icon-document' => __( 'Document Icon', 'sage' ),
                'icon-chat' => __( 'Chat Icon', 'sage' ),
                'icon-conversation' => __( 'Conversation Icon', 'sage' ),
                'icon-electricity' => __( 'Electricity Icon', 'sage' ),
                'icon-gas' => __( 'Gas Icon', 'sage' ),
                'icon-office' => __( 'Office Icon', 'sage' ),
                'icon-meters' => __( 'Meters Icon', 'sage' ),
                'icon-moving-truck' => __( 'Moving Truck', 'sage' ),
                'icon-computer' => __( 'Computer Icon', 'sage' ),
                'icon-pound' => __( 'British Pound', 'sage' ),
                'icon-windmill' => __( 'Wind Energy', 'sage' ),
                'icon-switch-to-us-icon' => __( 'Switch To Us', 'sage' )
              )
            ),
          // 'some_icon' => array(
          // 'type' => 'icon',
          // 'label' => __('Select an icon', 'widget-form-fields-text-domain'),
          // ),
          'widget_title' => array(
            'type' => 'text',
            'label' => __( 'Business Card Title' )
            )
          )
        ),
        'body_section' => array(
          'type' => 'section',
          'label' => __( 'Business Card Text' , 'sage' ),
          'hide' => false,
          'fields' => array(
            'a_repeater' => array(
              'type' => 'repeater',
              'label' => __( 'Business Card Text' , 'sage' ),
              'item_name'  => __( 'Repeater item', 'siteorigin-widgets' ),
              'fields' => array(
                'body_text' => array(
                  'type' => 'textarea',
                  'label' => __( 'Type a message', 'sage' ),
                  'rows' => 3
                )
              )
            ),
          )
        ),
        'button_section' => array(
          'type' => 'section',
          'label' => __('Select a Button Color and Text', 'sage'),
          'hide' => false,
          'fields' => array(
            'button_selection_body' => array(
              'type' => 'select',
              'label' => 'Choose a button for the body section',
              'prompt' => __( 'Choose a Button Colour', 'sage' ),
              'options' => array(
                'btn-primary' => __('Pink', 'sage'),
                'btn-default' => __('Green', 'sage')
              )
            ),
            'button_text_body' => array(
              'type' => 'text',
              'prompt' => __( 'Button Text', 'sage' ),
            ),
            'body_url' => array(
              'type' => 'link',
              'label' => __('Button Body URL', 'sage'),
              'default' => 'http://www.example.com'
            ),
            'button_selection_footer' => array(
              'type' => 'select',
              'label' => 'Choose a button for the footer section',
              'prompt' => __( 'Choose a Button Colour', 'sage' ),
              'options' => array(
                'btn-primary' => __('Pink', 'sage'),
                'btn-default' => __('Green', 'sage')
              )
            ),
            'button_text_footer' => array(
              'type' => 'text',
              'prompt' => __( 'Button Text', 'sage' ),
            ),
            'footer_url' => array(
              'type' => 'link',
              'label' => __('Footer Button URL', 'sage'),
              'default' => 'http://www.example.com'
            ),
          )
        ),
      ),

      //The $base_folder path string.
      plugin_dir_path(__FILE__)
    );
  }

  function get_template_name($instance) {
    return 'business-card-template';
  }

}

siteorigin_widget_register('business-card-widget', __FILE__, 'Business_Card_Widget');


text:
<?php

session_start();
require '../Autoloader.php';
Autoloader::register();
if(isset($_GET['dataSent']))
{
	$currYear = $_GET['dataSent'];

}
else
{
	$currYear = date('Y');
}
	$events = new Event();
	$tabEvent = $events->getListeEvent($currYear);
	$jsonDate = array();
	foreach ($tabEvent as $event) {
		$nbParticipant = $events->getNbPlaceAchete($event->dateEvent);
	    $jsonDate[] = array("dateEvent" => $event->dateEvent , 'titreEvent' => $event->titreEvent, 'libelleType' => $event->libelleType, 'nbPlaceEvent' => $event->nbPlaces, 'nbParticipant' => $nbParticipant);
	}
	echo json_encode($jsonDate);

?>


text:
author: Jeff Van Campen
comments: true
date: 2013-02-05 08:01:09+00:00
layout: post
slug: its-not-enough-to-just-show-up-and-do-the-work
title: Bring something to it
wordpress_id: 1032
category: notes
tags:
- Lynn Jennings
- motivation
- running
- self-reliance
---

It's not enough to just show up and do the work; you have to bring something to it. I tell that to runners all the time. It's not enough that you just log five miles. What was your intention? How effective were you at executing the workout? Was it an easy trot? That's OK, but if you were out there trying to do a workout, how focused on it were you on it? Really the bottom line is that if you're not believing with all fervor and relentlessness that you are capable of what it is you dream to do, no one else is going to believe that for you.

Lynn Jennings, [http://runneracademy.com/ra017-lynn-jennings/](http://runneracademy.com/ra017-lynn-jennings/)


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Threading;
using Zyan.Communication;
using Zyan.Communication.Security;
using Zyan.Communication.Protocols;
using Zyan.Communication.Protocols.Null;
using Zyan.Communication.Protocols.Tcp;

namespace Zyan.Tests
{
	#region Unit testing platform abstraction layer
#if NUNIT
	using NUnit.Framework;
	using TestClass = NUnit.Framework.TestFixtureAttribute;
	using TestMethod = NUnit.Framework.TestAttribute;
	using ClassInitializeNonStatic = NUnit.Framework.OneTimeSetUpAttribute;
	using ClassInitialize = DummyAttribute;
	using ClassCleanupNonStatic = NUnit.Framework.OneTimeTearDownAttribute;
	using ClassCleanup = DummyAttribute;
	using TestContext = System.Object;
#else
	using Microsoft.VisualStudio.TestTools.UnitTesting;
	using ClassInitializeNonStatic = DummyAttribute;
	using ClassCleanupNonStatic = DummyAttribute;
#endif
	#endregion

	/// <summary>
	/// Test class for TcpEx GetConnection lock issue. Issue #85
	/// </summary>
	[TestClass]
	public class TcpExConnectionLockRegressionTests
	{
		#region Sample component classes and interfaces

		/// <summary>
		/// Sample server interface.
		/// </summary>
		public interface ISampleServer
		{
			/// <summary>
			/// Returns a copy of the specified message.
			/// </summary>
			/// <param name="message">Message</param>
			/// <returns>Copy of message</returns>
			string Echo(string message);
		}

		/// <summary>
		/// Sample server implementation
		/// </summary>
		public class SampleServer : ISampleServer
		{
			/// <summary>
			/// Returns a copy of the specified message.
			/// </summary>
			/// <param name="message">Message</param>
			/// <returns>Copy of message</returns>
			public string Echo(string message)
			{
				return message;
			}
		}

		/// <summary>
		/// Encapsulated server hosting environment; Designed to run in a separate AppDomain.
		/// <remarks>
		/// The TCP Duplex Channel doesn´t support communication with client and server inside the same AppDomain.
		/// </remarks>
		/// </summary>
		public class TcpDuplexServerHostEnvironment : MarshalByRefObject, IDisposable
		{
			private static TcpDuplexServerHostEnvironment _instance = null;

			public static TcpDuplexServerHostEnvironment Instance
			{
				get
				{
					if (_instance == null)
						_instance = new TcpDuplexServerHostEnvironment();

					return _instance;
				}
			}

			private ZyanComponentHost _host;

			private TcpDuplexServerHostEnvironment()
			{
				var protocol = new TcpDuplexServerProtocolSetup(8092, new NullAuthenticationProvider(), true);
				_host = new ZyanComponentHost("TcpExConnectionLockRegressionTestHost_TcpDuplex", protocol);
				_host.RegisterComponent<ISampleServer, SampleServer>("SampleServer", ActivationType.SingleCall);
			}

			public void Dispose()
			{
				if (_host != null)
				{
					_host.Dispose();
					_host = null;
				}
			}
		}

		/// <summary>
		/// Component for locating the singleton instance of TcpDuplexServerHostEnvironment from another AppDomain.
		/// </summary>
		public class TcpDuplexServerHostEnvironmentLocator : MarshalByRefObject
		{
			public TcpDuplexServerHostEnvironment GetServerHostEnvironment()
			{
				return TcpDuplexServerHostEnvironment.Instance;
			}
		}

		#endregion

		#region Setup test environment and cleanup

		[ClassInitializeNonStatic]
		public void Initialize()
		{
			StartServers(null);
		}

		[ClassCleanupNonStatic]
		public void Cleanup()
		{
			StopServer();
		}

		// Application domain for TCP Duplex test environment Zyan host
		private static AppDomain _tcpDuplexServerAppDomain = null;

		[ClassInitialize]
		public static void StartServers(TestContext ctx)
		{
			// Setup TCP Duplex Server AppDomain
			AppDomainSetup tcpDuplexAppDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) };
			_tcpDuplexServerAppDomain = AppDomain.CreateDomain("RecreateClientConnectionTests_Server", null, tcpDuplexAppDomainSetup);
			_tcpDuplexServerAppDomain.Load(typeof(ZyanConnection).Assembly.GetName());

			// Start Zyan host inside the TCP Duplex Server AppDomain
			var tcpDuplexServerWork = new CrossAppDomainDelegate(() =>
			{
				var server = TcpDuplexServerHostEnvironment.Instance;

				if (server != null)
				{
					Console.WriteLine("TCP Duplex Server running.");
				}
			});
			_tcpDuplexServerAppDomain.DoCallBack(tcpDuplexServerWork);
		}

		[ClassCleanup]
		public static void StopServer()
		{
			Trace.WriteLine("** Stopping the server! **");

			try
			{
				CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() =>
				{
					TcpDuplexServerHostEnvironment.Instance.Dispose();
				});
				_tcpDuplexServerAppDomain.DoCallBack(serverWork);
			}
			finally
			{
				AppDomain.Unload(_tcpDuplexServerAppDomain);
			}
		}

		#endregion

		[TestMethod]
		public void CreateDisposeAndRecreateConnectionUsingTcpDuplexChannel()
		{
			var url = "tcpex://localhost:8092/TcpExConnectionLockRegressionTestHost_TcpDuplex";
			var protocol = new TcpDuplexClientProtocolSetup(true);
			var lessThanTimeout = 10;

			using (var connection = new ZyanConnection(url, protocol))
			{
				var sw = Stopwatch.StartNew();
				var proxy = connection.CreateProxy<ISampleServer>("SampleServer");
				var badConnectionInitiated = false;

				for (var i = 0; i < 100; i++)
				{
					var echo = "Hi" + i;
					Assert.AreEqual(echo, proxy.Echo(echo));
					Thread.Sleep(10);

					// make sure that proxy is already created and runs
					if (i == 3)
					{
						Trace.WriteLine("** Spawning a thread for another tcpex connection **");
						ThreadPool.QueueUserWorkItem(x =>
						{
							badConnectionInitiated = true;

							try
							{
								// this connection should time out in more than lessThanTimeout seconds
								new ZyanConnection(url.Replace("localhost", "example.com"), protocol);
							}
							catch (Exception ex)
							{
								// this exception is expected
								Trace.WriteLine("** Connection failed as expected **:" + ex.Message);
							}
						});
					}
				}

				sw.Stop();

				Assert.IsTrue(badConnectionInitiated);
				Assert.IsTrue(sw.Elapsed.TotalSeconds < lessThanTimeout);
				Trace.WriteLine("** CreateDisposeAndRecreateConnectionUsingTcpDuplexChannel test finished **");
			}
		}
	}
}


text:
package com.ghgande.j2mod.modbus.msg;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.net.AbstractModbusListener;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Class implementing a <tt>Read MEI Data</tt> request.
 *
 * @author Julie Haugh (jfh@ghgande.com)
 * @author jfhaugh (jfh@ghgande.com)
 * @author Steve O'Hara (4energy)
 * @version 2.0 (March 2016)
 */
public final class ReportSlaveIDRequest extends ModbusRequest {

    /**
     * Constructs a new <tt>Report Slave ID request</tt>
     * instance.
     */
    public ReportSlaveIDRequest() {
        super();

        setFunctionCode(Modbus.REPORT_SLAVE_ID);

        // There is no additional data in this request.
        setDataLength(0);
    }

    /**
     * createResponse -- create an empty response for this request.
     * @return
     */
    public ModbusResponse getResponse() {
        ReportSlaveIDResponse response;

        response = new ReportSlaveIDResponse();

        // Copy any header data from the request.
        response.setHeadless(isHeadless());
        if (!isHeadless()) {
            response.setTransactionID(getTransactionID());
            response.setProtocolID(getProtocolID());
        }

        // Copy the unit ID and function code.
        response.setUnitID(getUnitID());
        response.setFunctionCode(getFunctionCode());

        return response;
    }

    @Override
    public ModbusResponse createResponse(AbstractModbusListener listener) {
        return createExceptionResponse(Modbus.ILLEGAL_FUNCTION_EXCEPTION);
    }

    /**
     * writeData -- output this Modbus message to dout.
     * @throws java.io.IOException
     */
    public void writeData(DataOutput dout) throws IOException {
        dout.write(getMessage());
    }

    /**
     * readData -- dummy function.  There is no data with the request.
     * @throws java.io.IOException
     */
    public void readData(DataInput din) throws IOException {
    }

    /**
     * getMessage
     * @return an empty array as there is no data for this request
     */
    public byte[] getMessage() {

        return new byte[0];
    }
}


text:
#import <Cocoa/Cocoa.h>

@class ResourceManager;
@class ResourceManagerOutlineHandler;

@interface ResourceManagerPanel : NSWindowController<NSOutlineViewDelegate, NSOutlineViewDataSource, NSSplitViewDelegate>
{
    IBOutlet NSOutlineView* resourceList;
    IBOutlet NSImageView* imagePreview;
    IBOutlet NSTextField* lblNoPreview;

    ResourceManagerOutlineHandler* outlineHandler;

    //ResourceManager* resManager;
    //int resType;
}

//@property (nonatomic,readonly) ResourceManager* resManager;

@property (nonatomic,assign) int resType;

- (void) reload;

@end


text:
<?php
declare(strict_types = 1);

namespace FabysCore\Component\Database;

use FabysCore\Component\Database\Entity\Entity;
use Psr\Http\Message\{
    ResponseInterface, ServerRequestInterface
};

/**
 * Database
 *
 * @category Component
 * @package Database
 * @author Fabian Pfeiffer <info@fabysdev.com>
 */
class Database
{
    /**
     * @const REQUEST_ATTRIBUTE request attribute name
     */
    const REQUEST_ATTRIBUTE = ".database";

    /**
     * @var \PDO
     */
    private $pdo;

    /**
     * @var array
     */
    private $repositories = [];

    /**
     * @param string|\PDO $pdo
     * @param string $username
     * @param string $password
     */
    public function __construct($pdo, string $username = "", string $password = "") {
        if(!$pdo instanceof \PDO) {
            $pdo = new \PDO($pdo, $username, $password);
        }

        $this->pdo = $pdo;
        $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }

    /**
     * adds the database to the request attributes
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable $next
     * @return ResponseInterface
     */
    public function init(ServerRequestInterface $request, ResponseInterface $response, callable $next) {
        return $next($request->withAttribute(self::REQUEST_ATTRIBUTE, $this), $response);
    }

    /**
     * adds or updates an entity
     *
     * @param Entity $entity
     */
    public function save(Entity $entity) {
        if($entity->isPersisted) {
            $this->updateEntity($entity);
        }else {
            $this->insertEntity($entity);
        }
    }

    /**
     * removes an entity from the database
     *
     * @param Entity $entity
     * @throws \RuntimeException throws if the entity is not persisted
     */
    public function delete(Entity $entity) {
        if(!$entity->isPersisted) {
            throw new \RuntimeException(sprintf("You can not delete an non persisted Entity of type '%s'", get_class($entity)));
        }

        $config = $entity::configure();

        $sql = sprintf("DELETE FROM %s WHERE %s = :id", $config["table"], $config["identifier"]);

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue(":id", $entity->get($config["identifier"]), $config["data"][$config["identifier"]]);

        $stmt->execute();
    }

    /**
     * @return \PDO
     */
    public function getConnection() {
        return $this->pdo;
    }

    /**
     * returns the entity repository for a given entity class
     *
     * @param string $class
     * @return mixed
     */
    public function getRepository(string $class) {
        if(isset($this->repositories[$class])) {
            return $this->repositories[$class];
        }

        assert((function ($class) {
            $c = new \ReflectionClass($class);

            return $c->hasMethod("configure");
        })($class), sprintf("Entity '%s' must be an instance of '\\FabysCore\\Component\\Database\\Entity\\Entity'", $class));

        /* @var $class Entity */
        $config = $class::configure();

        if(!isset($config["repository_class"]) || !isset($config["repository_class"][0])) {
            $repositoryClass = "FabysCore\\Component\\Database\\Entity\\Repository";
        }else {
            $repositoryClass = $config["repository_class"];
        }

        /* @var $class string */
        $repository = new $repositoryClass($this, $config, $class);
        $this->repositories[$class] = $repository;

        return $repository;
    }

    /**
     * inserts a new entity into the database
     *
     * @param Entity $entity
     */
    private function insertEntity(Entity $entity) {
        $config = $entity::configure();

        $fields = array_keys($config["data"]);
        $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $config["table"], implode(", ", $fields), ":".implode(", :", $fields));

        $stmt = $this->pdo->prepare($sql);

        foreach($config["data"] as $k => $v) {
            $stmt->bindValue(":".$k, $entity->get($k), $v);
        }

        $stmt->execute();

        $entity->setLastInsertId($this->pdo->lastInsertId());
        $entity->isPersisted = true;
        $entity->setDatabase($this);
        $entity->updated = [];
    }

    /**
     * updates the database record for an entity
     *
     * @param Entity $entity
     */
    private function updateEntity(Entity $entity) {
        if(empty($entity->updated)) {
            return;
        }
        $updated = array_keys($entity->updated);

        $config = $entity::configure();

        $updateSql = "";
        $j = 1;
        foreach($updated as $key) {
            if($j > 1) {
                $updateSql .= ", ";
            }
            $updateSql .= $key." = :".$key;
            $j++;
        }

        $sql = sprintf("UPDATE %s SET %s WHERE %s = :id", $config["table"], $updateSql, $config["identifier"]);

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue(":id", $entity->get($config["identifier"]), $config["data"][$config["identifier"]]);

        foreach($updated as $key) {
            $stmt->bindValue(":".$key, $entity->get($key), $config["data"][$key]);
        }

        $stmt->execute();

        $entity->updated = [];
    }
}


text:
<?php

namespace Code4mk\Multitrust\Exceptions;

class LevelDeniedException extends AccessDeniedException
{
    /**
     * Create a new level denied exception instance.
     *
     * @param string $level
     */
    public function __construct($level)
    {
        $this->message = sprintf("You don't have a required [%s] level.", $level);
    }
}


text:
using JsonSubTypes;
using Newtonsoft.Json;
using System;

namespace Test {
    [JsonConverter(typeof(JsonSubtypes), "type")][JsonSubtypes.KnownSubType(typeof(RootInterface.Foo), "Foo")]
    public abstract class RootInterface {
        [JsonProperty("type", Required = Required.DisallowNull)]
        private String TypeField {
            get;
        }

        public RootInterface(String TypeField) {
            this.TypeField = TypeField;
        }

        [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
        public class Foo : RootInterface {

            [JsonConstructor]
            public Foo (
                [JsonProperty("type", Required = Required.DisallowNull)] String TypeField
            ) : base(TypeField) {}

            public override bool Equals(Object other) {
                Foo o = other as Foo;

                if (o == null) {
                    return false;
                }

                return true;
            }

            public override int GetHashCode() {
                int result = 1;
                return result;
            }

            public override String ToString() {
                return "Foo()";
            }
        }
    }
}


text:
include $(TOPDIR)/rules.mk

LUCI_TITLE:=RSA/X.509 Key Generator (required for LuCId SSL support)
LUCI_DEPENDS:=+lua +luci-lib-nixio

PKG_USE_MIPS16:=0
PKG_LICENSE:=LGPL-2.1

include ../../luci.mk

# call BuildPackage - OpenWrt buildroot signature


text:
/* $Id$  */

package org.apache.lenya.workflow;

/**
 * Boolean variable assignment.
 */
public interface BooleanVariableAssignment extends Action {
    // do nothing
}


text: Research - general


text:
module Rnotifier
  class ParameterFilter

    DEFAULT_FIELDS = [:password, :password_confirmation, :authorization, :secret, :passwd]
    FILTERED = '[FILTERED]'

    def self.filter(params, filters)
      @filter ||= ParameterFilter.new(filters)
      @filter.filter(params)
    end

    def self.default_filter(params)
      @default_filter ||= ParameterFilter.new(DEFAULT_FIELDS)
      @default_filter.filter(params)
    end

    def initialize(filters)
      @filters = filters
    end

    def filter(params)
      if @filters && !@filters.empty?
        compiled_filter.call(params)
      else
        params
      end
    end

    private

    def compiled_filter
      @compiled_filter ||= begin
      regexps, blocks = compile_filter

        lambda do |original_params|
          filtered_params = {}

          original_params.each do |key, value|
            if regexps.find { |r| key =~ r }
              value = FILTERED
            elsif value.is_a?(Hash)
              value = filter(value)
            elsif value.is_a?(Array)
              value = value.map { |v| v.is_a?(Hash) ? filter(v) : v }
            elsif blocks
              key = key.dup
              value = value.dup rescue value
              blocks.each { |b| b.call(key, value) }
            end

            filtered_params[key] = value
          end

          filtered_params
        end
      end
    end

    def compile_filter
      strings, regexps, blocks = [], [], []

      @filters.each do |item|
        case item
        when NilClass
        when Proc
          blocks << item
        when Regexp
          regexps << item
        else
          strings << item.to_s
        end
      end

      regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
      [regexps, blocks]
    end
  end
end


text:
set -e

# detect java location
JAVA_HOME="$(readlink -f /usr/bin/java | sed "s:/jre/bin/java::")"
java="${JAVA_HOME}/bin/java"

# Logging
LOG_CONFIG=${LOG_CONFIG:-/etc/elastisys/spotpool/logback.xml}
JUL_CONFIG=${JUL_CONFIG:-/etc/elastisys/spotpool/logging.properties}
# log destination dir for default LOG_CONFIG
LOG_DIR=${LOG_DIR:-/var/log/elastisys/spotpool}
mkdir -p ${LOG_DIR}
STDOUT_LOG_LEVEL=${STDOUT_LOG_LEVEL:-INFO}

#
# Runtime configuration
#

# where runtime state is kept
STORAGE_DIR=${STORAGE_DIR:-/var/lib/elastisys/spotpool}

RUNTIME_OPTS="--storage-dir ${STORAGE_DIR}"

#
# HTTP/HTTPS configuration
#

[[ -z "${HTTP_PORT}" && -z "${HTTPS_PORT}" ]] && echo "error: neither HTTP_PORT nor HTTPS_PORT specified" && exit 1

SERVER_OPTS=""
if [ "${HTTP_PORT}" != "" ]; then
    SERVER_OPTS="${SERVER_OPTS} --http-port=${HTTP_PORT}"
fi

# TLS/SSL settings
if [ "${HTTPS_PORT}" != "" ]; then
    SERVER_OPTS="${SERVER_OPTS} --https-port=${HTTPS_PORT}"
    [ -z "${SSL_KEYSTORE}" ] && echo "error: no SSL_KEYSTORE specified" && exit 1
    [ -z "${SSL_KEYSTORE_PASSWORD}" ] && echo "error: no SSL_KEYSTORE_PASSWORD specified" && exit 1
    SERVER_OPTS="${SERVER_OPTS} --ssl-keystore ${SSL_KEYSTORE} --ssl-keystore-password ${SSL_KEYSTORE_PASSWORD}"
fi

#
# Client authentication settings
#

# basic authentication
REQUIRE_BASIC_AUTH=${REQUIRE_BASIC_AUTH:-false}
# cert authentication
REQUIRE_CERT_AUTH=${REQUIRE_CERT_AUTH:-false}

AUTH_OPTS=""
# require clients to do basic authentication against a security realm
if ${REQUIRE_BASIC_AUTH} ; then
    [ -z "${BASIC_AUTH_REALM_FILE}" ] && echo "error: no BASIC_AUTH_REALM_FILE specified" && exit 1
    [ -z "${BASIC_AUTH_ROLE}" ] && echo "error: no BASIC_AUTH_ROLE specified" && exit 1
    AUTH_OPTS="${AUTH_OPTS} --require-basicauth --require-role ${BASIC_AUTH_ROLE} --realm-file ${BASIC_AUTH_REALM_FILE}"
fi
# require clients to authenticate with a trusted certificate
if ${REQUIRE_CERT_AUTH} ; then
    [ -z "${CERT_AUTH_TRUSTSTORE}" ] && echo "error: no CERT_AUTH_TRUSTSTORE specified" && exit 1
    [ -z "${CERT_AUTH_TRUSTSTORE_PASSWORD}" ] && echo "error: no CERT_AUTH_TRUSTSTORE_PASSWORD specified" && exit 1
    AUTH_OPTS="${AUTH_OPTS} --require-cert -ssl-truststore ${CERT_AUTH_TRUSTSTORE} --ssl-truststore-password ${CERT_AUTH_TRUSTSTORE_PASSWORD}"
fi

#
# Java system properties
#

JVM_OPTS=${JVM_OPTS:--Xmx128m}
JAVA_OPTS="-Djava.net.preferIPv4Stack=true -Djava.util.logging.config.file=${JUL_CONFIG} -Dlogback.configurationFile=${LOG_CONFIG}"
# On SIGQUIT: make sure a thread dump written to ${LOG_DIR}/jvm.log
JAVA_OPTS="${JAVA_OPTS} -XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput -XX:LogFile=${LOG_DIR}/jvm.log -XX:-PrintConcurrentLocks"
# On OutOfMemory errors write a java_pid<pid>.hprof file to ${LOG_DIR}
JAVA_OPTS="${JAVA_OPTS} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${LOG_DIR} "
JAVA_OPTS="${JAVA_OPTS} -DLOG_DIR=${LOG_DIR}"

#
# Start
#

if [ "${MULTIPOOL}" = true ]; then
    ${java} ${JVM_OPTS} ${JAVA_OPTS} -cp /opt/elastisys/spotpool/spotpool.jar com.elastisys.scale.cloudpool.aws.spot.server.multipool.Main ${RUNTIME_OPTS} ${SERVER_OPTS} ${AUTH_OPTS}
else
    ${java} ${JVM_OPTS} ${JAVA_OPTS} -jar /opt/elastisys/spotpool/spotpool.jar ${RUNTIME_OPTS} ${SERVER_OPTS} ${AUTH_OPTS}
fi


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lichenologist 40(3): 200 (2008)

#### Original name
Myochroidea minutula Printzen, T. Sprib. & Tønsberg

### Remarks
null


text:
package lists;

import java.util.Arrays;

/**
 * Created by seanking on 10/03/2017.
 */
public class MyArrayList{

    int[] array;
    private static final int DEFAULT_CAPACITY = 10;
    int size = 0;

    public MyArrayList(){
        array = new int[DEFAULT_CAPACITY];
    }

    //add an element to the list
    public void add(int element){
        if(isFull()){
            newMaxCapacity();
        }
        array[size] = element;
        size++;
    }

    //create a new array with double the size of the previou array
    private void newMaxCapacity() {
        int newSize = array.length * 2;
        array = Arrays.copyOf(array, newSize);
    }

    //check if the array is full
    public boolean isFull() {
        if(array.length == size){
            return true;
        }
        return false;
    }

    public boolean isEmpty(){
        if(size == 0){
            return true;
        }
        return false;
    }
    //remove an element at position indix
    public void remove(int index){
        if(isEmpty()){
            System.out.println("The list is empty");
        }
        else if(index >= size){
            System.out.println("No element at index " + index);
        }
        else{
            for(int i = index; i < size - 1; i++){
                array[i] = array[i + 1];
            }
            size--;
        }
    }

    @SuppressWarnings("unchecked")
    private int elementData(int index) {
        return array[index];
    }

    public int get(int index){
        if(isEmpty())
            System.out.println("List is empty");
        else if(index > size - 1)
            System.out.println("Index out of bounds");
        else
            return elementData(index);
        return -1;
    }

    //display all the elements int the list
    public void displayList(){
        if(isEmpty())
            System.out.println("The list is empty");
        else{
            for(int i = 0; i < size; i++){
                System.out.print(array[i] + " ");
            }
            System.out.println();
        }
    }

    public void sort(){
        int[] newArray = new int[size];
        for(int i = 0; i < size; i++)
            newArray[i] = array[i];
        array = mergeSort(newArray);
    }

    //merge sort uses a divide and conqeur approach
    //time complexity o(n log n)
    //space complexity o(n)
    private int[] mergeSort(int[] array) {
        //variable for length of array
        int n = array.length;
        //if we have one element left in the array return - base statement
        if(n < 2 ) return null;
        //mid point is n / 2
        int mid = n / 2;
        //create left and right arrays
        int[] left = new int[mid];
        int[] right = new int[n - mid];
        //populate the arrays
        for(int i = 0; i < mid; i ++){
            left[i] = array[i];
        }
        for(int i = mid; i < n; i++){
            right[i - mid] = array[i];
        }
        //sort the left array
        mergeSort(left);
        //sort the right array
        mergeSort(right);
        //returns two sorted arrays merged together
        return array = merge(left, right, array);
    }

    //merges two sorted array
    private int[] merge(int[] left, int[] right, int[] array) {
        int l = left.length;
        int r = right.length;
        //i for left list, j for righ list and k for array
        int i = 0, j = 0, k = 0;

        //while we have not reached the end of either array to be merged
        while(i < left.length && j < right.length){
            //if the element at i in the left array is less than or equal to the element j in the right array
            //element k in array is equal to element i in left array
            if(left[i] <= right[j]){
                array[k] = left[i];
                i++;
            }
            //otherwise it is equal to element j in right array
            else{
                array[k] = right[j];
                j++;
            }
            k++;
        }
        //if there is elements left in left array add to main array
        while(i < l){
            array[k] = left[i];
            i++;
            k++;
        }
        //otherwise add the elements left in the right array to main array
        while(j < r){
            array[k] = right[j];
            j++;
            k++;
        }
        //return the newly sorted array
        return array;
    }
}


text:
<?php

namespace Bundle\CommonBundle\Command;

use Bundle\CommonBundle\Entity\UsersGroups\UsersGroups;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Bundle\CommonBundle\Entity\User\User;
use Symfony\Component\DomCrawler\Crawler;
use Bundle\CommonBundle\Entity\Group\Group;

/**
 * Синхронизация групп из PS
 * @author Pavel Plutakhin <pavel.plutakhin@simbirsoft.com>
 */
class SyncGroupsCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('ps:sync:groups')
            ->setDescription('Обновление групп из PS');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();
        $userRepository = $container->get('user.repository');
        $groupRepository = $container->get('group.repository');
        $usersGroupsRepository = $container->get('usersgroups.repository');

        $login = $container->getParameter('ps.sync.users.login');
        $pass = $container->getParameter('ps.sync.users.pass');
        $authBase64 = base64_encode(sprintf('%s:%s', $login, $pass));

        $url = $container->getParameter('ps.sync.groups.url');

        $opts = array('http' => array(
            'method' => 'GET',
            'header' => "Content-Type: text/xml\r\n" .
            "Authorization: Basic " . $authBase64 . "\r\n",
            'content' => '',
            'timeout' => 60
        ));
        $context = stream_context_create($opts);

        if (! $xml = @file_get_contents($url, false, $context)) {
            $output->writeln('Bad url or login pass filed, cannot get content');
            return;
        }

        $crawler = new Crawler();
        $xml = simplexml_load_string($xml);
        foreach ($xml->group as $xmlGroup) {
            $name = (string) $xmlGroup->attributes()->name;
            if (! $group = $groupRepository->findOneByName($name)) {
                $group = new Group();
                $group->setName($name);
            }

            $members = array();
            // Добавляем участников в группу
            foreach ($xmlGroup->user as $xmlUser) {
                $id = $xmlUser->attributes()->id;
                $members[] = $id;
                if ($user = $userRepository->findOneByPs($id)) {
                    if (!$usersGroupsRepository->isExists($user, $group)) {
                        $ug = new UsersGroups();
                        $ug->setUser($user);
                        $ug->setGroup($group);
                        $ug->setManual(false);
                        $usersGroupsRepository->save($ug);
                        $output->writeln(sprintf('added %s in %s', $user->getFullName(), $group->getName()));
                    }
                }
            }
            //Удаляем участников из группы
            foreach ($group->getUsersGroups() as $ug) {
                /** @var User $user */
                $user = $ug->getUser();
                if (!in_array($user->getPs(), $members) && !$ug->getManual()) {
                    $usersGroupsRepository->remove($ug);
                    $output->writeln(sprintf('removed %s from %s', $user->getFullName(), $group->getName()));
                }
            }
        }

        $output->writeln('Done');
    }
}


text:
package io.dropwizard.views.freemarker;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import freemarker.core.HTMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.Template;
import freemarker.template.Version;
import io.dropwizard.views.View;
import io.dropwizard.views.ViewRenderException;
import io.dropwizard.views.ViewRenderer;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * A {@link ViewRenderer} which renders Freemarker ({@code .ftl, .ftlh or .ftlx}) templates.
 */
public class FreemarkerViewRenderer implements ViewRenderer {
    private static final Pattern FILE_PATTERN = Pattern.compile("\\.ftl[hx]?");
    private final TemplateLoader loader;

    private static class TemplateLoader implements CacheLoader<Class<?>, Configuration> {
        private final Version incompatibleImprovementsVersion;
        private Map<String, String> baseConfig = Collections.emptyMap();

        private TemplateLoader(Version incompatibleImprovementsVersion) {
            this.incompatibleImprovementsVersion = incompatibleImprovementsVersion;
        }

        @Override
        public Configuration load(@Nonnull Class<?> key) throws Exception {
            final Configuration configuration = new Configuration(incompatibleImprovementsVersion);
            configuration.setObjectWrapper(new DefaultObjectWrapperBuilder(incompatibleImprovementsVersion).build());
            configuration.loadBuiltInEncodingMap();
            configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
            configuration.setClassForTemplateLoading(key, "/");
            // setting the outputformat implicitly enables auto escaping
            configuration.setOutputFormat(HTMLOutputFormat.INSTANCE);
            for (Map.Entry<String, String> entry : baseConfig.entrySet()) {
                configuration.setSetting(entry.getKey(), entry.getValue());
            }
            return configuration;
        }

        void setBaseConfig(Map<String, String> baseConfig) {
            this.baseConfig = baseConfig;
        }
    }

    private final LoadingCache<Class<?>, Configuration> configurationCache;

    /**
     * @deprecated Use {@link #FreemarkerViewRenderer(Version)} instead.
     */
    public FreemarkerViewRenderer() {
        this(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    }

    /**
     * @param incompatibleImprovementsVersion FreeMarker version number for backward compatible bug fixes and improvements.
     *                                        See {@link Configuration#Configuration(Version)} for more information.
     */
    public FreemarkerViewRenderer(Version incompatibleImprovementsVersion) {
        this.loader = new TemplateLoader(incompatibleImprovementsVersion);
        this.configurationCache = Caffeine.newBuilder().build(loader);
    }

    @Override
    public boolean isRenderable(View view) {
        return FILE_PATTERN.matcher(view.getTemplateName()).find();
    }

    @Override
    public void render(View view,
                       Locale locale,
                       OutputStream output) throws IOException {
        final Configuration configuration = configurationCache.get(view.getClass());
        if (configuration == null) {
            throw new ViewRenderException("Couldn't find view class " + view.getClass());
        }

        try {
            final Charset charset = view.getCharset().orElseGet(() -> Charset.forName(configuration.getEncoding(locale)));
            final Template template = configuration.getTemplate(view.getTemplateName(), locale, charset.name());
            template.process(view, new OutputStreamWriter(output, template.getEncoding()));
        } catch (Exception e) {
            throw new ViewRenderException(e);
        }
    }

    @Override
    public void configure(Map<String, String> baseConfig) {
        this.loader.setBaseConfig(baseConfig);
    }

    @Override
    public String getConfigurationKey() {
        return "freemarker";
    }
}


text:
<?php

use App\Label;
use App\Folder;
use App\Setting;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Model::unguard();

		Label::create(['name' => 'favorite']);
        Label::create(['name' => 'trashed']);

        Setting::insert([
            ['name' => 'homeTagline', 'value' => 'BeDrive. A new home for your files.'],
            ['name' => 'homeByline', 'value' => 'Register or Login now to upload, backup, manage and access your files on any device, from anywhere, free.'],
            ['name' => 'homeButtonText', 'value' => 'Register Now'],
            ['name' => 'homepage', 'value' => 'landing'],
            ['name' => 'blacklist', 'value' => 'exe, application/x-msdownload, x-dosexec'],
            ['name' => 'maxFileSize', 'value' => 20],
            ['name' => 'maxUserSpace', 'value' => 104857600],
            ['name' => 'enableRegistration', 'value' => 1],
            ['name' => 'siteName', 'value' => 'BeDrive'],
            ['name' => 'enableHomeUpload', 'value' => 1],
            ['name' => 'maxSimultUploads', 'value' => 10],
            ['name' => 'enablePushState', 'value' => 0],
            ['name' => 'dateLocale', 'value' => 'en'],
            ['name' => 'pushStateRootUrl', 'value' => '/'],
            ['name' => 'disqusShortname', 'value' => 'bedrive'],
            ['name' => 'enablePayments', 'value' => 1],
        ]);
	}

}


text:
/* */
"format global";
"use strict";

var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

exports.Identifier = Identifier;
exports.__esModule = true;

var levenshtein = _interopRequire(require("leven"));

var messages = _interopRequireWildcard(require("../../../messages"));

var optional = true;

exports.optional = optional;

function Identifier(node, parent, scope, file) {
  if (!this.isReferenced()) return;
  if (scope.hasBinding(node.name)) return;

  // get the closest declaration to offer as a suggestion
  // the variable name may have just been mistyped

  var bindings = scope.getAllBindings();

  var closest;
  var shortest = -1;

  for (var name in bindings) {
    var distance = levenshtein(node.name, name);
    if (distance <= 0 || distance > 3) continue;
    if (distance <= shortest) continue;

    closest = name;
    shortest = distance;
  }

  var msg;
  if (closest) {
    msg = messages.get("undeclaredVariableSuggestion", node.name, closest);
  } else {
    msg = messages.get("undeclaredVariable", node.name);
  }

  //

  throw file.errorWithNode(node, msg, ReferenceError);
}


text:
'use strict';
var stream = require('stream');
var Transform = stream.Transform;

module.exports = function ReplaceStream(search, replace, options) {
  var tail = '';
  var totalMatches = 0;
  var isRegex = search instanceof RegExp;

  options = options || {};
  options.limit = options.limit || Infinity;
  options.encoding = options.encoding || 'utf8';
  options.maxMatchLen = options.maxMatchLen || 100;

  var replaceFn = replace;

  replaceFn = createReplaceFn(replace, isRegex);

  var match;
  if (isRegex) {
    match = matchFromRegex(search, options)
  } else {
    throw new Error('need RegExp search');
  }

  function transform(buf, enc, cb) {
    var matches;
    var lastPos = 0;
    var runningMatch = '';
    var matchCount = 0;
    var rewritten = '';
    var haystack = tail + buf.toString(options.encoding);
    tail = '';

    while (totalMatches < options.limit &&
          (matches = match.exec(haystack)) !== null) {

      matchCount++;
      var before = haystack.slice(lastPos, matches.index);
      var regexMatch = matches;
      lastPos = matches.index + regexMatch[0].length;

      if (lastPos > haystack.length && regexMatch[0].length < options.maxMatchLen) {
        tail = regexMatch[0]
      } else {
        var dataToAppend = getDataToAppend(before,regexMatch);
        rewritten += dataToAppend;
      }
    }

    if (tail.length < 1)
      tail = haystack.slice(lastPos) > options.maxMatchLen ? haystack.slice(lastPos).slice(0 - options.maxMatchLen) : haystack.slice(lastPos)

    var dataToQueue = getDataToQueue(matchCount,haystack,rewritten,lastPos);
    cb(null, dataToQueue);
  }

  function getDataToAppend(before, match) {
    var dataToAppend = before;

    totalMatches++;

    dataToAppend += isRegex ? replaceFn.apply(this, match.concat([match.index, match.input])) : replaceFn(match[0]);

    return dataToAppend;
  }

  function getDataToQueue(matchCount, haystack, rewritten, lastPos) {
    if (matchCount > 0) {
      if (haystack.length > tail.length) {
        return rewritten + haystack.slice(lastPos, haystack.length - tail.length);
      }

      return rewritten;
    }

    return haystack.slice(0, haystack.length - tail.length);
  }

  function flush(cb) {
    if (tail) {
      this.push(tail);
    }
    cb();
  }

  return new Transform({
    transform: transform,
    flush: flush
  });
};

function createReplaceFn(replace, isRegEx) {
  var regexReplaceFunction = function () {
    var newReplace = replace;
    // ability to us $1 with captures
    // Start at 1 and end at length - 2 to avoid the match parameter and offset
    // And string parameters
    var paramLength = arguments.length - 2;
    for (var i = 1; i < paramLength; i++) {
      newReplace = newReplace.replace('$' + i, arguments[i] || '')
    }
    return newReplace;
  };

  if (isRegEx && !(replace instanceof Function)) {
    return regexReplaceFunction;
  }

  if (!(replace instanceof Function)) {
    return function stringReplaceFunction() {
      return replace;
    };
  }

  return replace;
}

function matchFromRegex(regex, options) {
  if (options.regExpOptions) {
    regex = new RegExp(regex.source, options.regExpOptions)
  }

  // If there is no global flag then there can only be one match
  if (!regex.global) {
    options.limit = 1;
  }
  return regex;
}


text:
import {Component} from '@angular/core';

@Component({
  selector: 'progress-bar-e2e',
  templateUrl: 'progress-bar-e2e.html',
  styles: [
    `
    mat-progress-bar {
      margin-bottom: 10px;
    }
  `,
  ],
})
export class ProgressBarE2E {
  determinateValue: number = 57;
  bufferValue: number = 35;
}


text:
include_recipe "ttx_common::monit-service"
include_recipe "ttx_hbase::hbase-services"

SERVICE='hbase-regionserver'

template "monit-#{SERVICE}" do
    path "#{node[:ttx][:monit][:conf_dir]}/#{SERVICE}.monitrc"
    cookbook "ttx_common"
    source "basic-monitrc.conf.erb"
    mode 0644
    variables({
        :monit_service => "#{SERVICE}",
        :monit_check_type => 'pidfile',
        :monit_service_check_target  => "#{node[:ttx_hbase][:hbase][:pid_dir]}/hbase-#{node[:ttx_hbase][:hbase][:user]}-regionserver.pid",
        :monit_service_group => 'hbase'
    })
    notifies :restart, "service[monit]"

    action :nothing
end

execute "start-hbase-regionserver" do
	command "echo starting hbase regionserver..."
    notifies :enable, resources(:service => "#{SERVICE}")
    notifies :restart, resources(:service => "#{SERVICE}")

    notifies :create, resources(:template => "monit-#{SERVICE}")
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <property name="CONSOLE_LOG_PATTERN"
    value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr([%18.18t]){faint} %clr(%-65.65logger{64}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
  <property name="FILE_LOG_PATTERN"
    value="%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} [%18.18t] %-65.65logger{64} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
  <property name="LOG_PATH" value="." />

  <include resource="org/springframework/boot/logging/logback/base.xml" />

  <logger name="com.redhat.issues" level="DEBUG" />
  <logger name="org.apache" level="INFO" />
  <logger name="org.apache.activemq" level="DEBUG" />
  <logger name="org.apache.activemq.transport.failover" level="DEBUG" />
  <logger name="org.jboss" level="INFO" />
  <logger name="org.springframework" level="INFO" />
  <logger name="org.springframework.jms" level="DEBUG" />
  <logger name="org.springframework.jms.listener" level="DEBUG" />

</configuration>


text:
package eu.davidea.flexibleadapter.databinding;

import androidx.databinding.BindingAdapter;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import eu.davidea.flexibleadapter.FlexibleAdapter;
import eu.davidea.flexibleadapter.items.IFlexible;

public class BindingAdapters {

    @SuppressWarnings("unchecked")
    @BindingAdapter(value = "items")
    public static <T extends IFlexible> void setAdapter(RecyclerView recyclerView, List<T> items) {
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null && adapter instanceof FlexibleAdapter) {
            ((FlexibleAdapter<T>) adapter).updateDataSet(items);
        } else {
            throw new IllegalStateException("Binding works only with FlexibleAdapter");
        }
    }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
in Brunner & Redtenbacher, Ins. -Fam. Phasm. , 182, 208.

#### Original name
null

### Remarks
null


text:
FactoryGirl.define do
  factory :category, :class => 'FormolApi::Category' do
    sequence(:name){ |i| "Category_#{i}" }

    trait :second_in_list do
      position 2
    end
  end
end


text:
<?php

/**
 * Event Exception
 *
 * @package     Nails
 * @subpackage  common
 * @category    Exceptions
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Common\Exception;

class EventException extends NailsException
{
}


text:
require 'grep/outputter/saving'
require 'grep/outputter/unwilling'

module Grep
  module Outputter
  end
end


text:
FROM ppc64le/ubuntu:16.04

#Maintainer details
MAINTAINER Sandip Giri

#Install all required dependencies
RUN     apt-get update \
        && apt-get install -y git build-essential libtool m4 automake linux-headers-$(uname -r)

#Clone and build lustre-client
RUN git clone git://git.hpdd.intel.com/fs/lustre-release.git && \
cd lustre-release && \
sh autogen.sh && \
./configure --with-linux=/lib/modules/$(uname -r)/build/ && \
make && \
make install


text:
<?php
/**
 * Hush Framework
 *
 * @category   Hush
 * @package    Hush_Document_Parser
 * @author     James.Huang <shagoo@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0
 * @version    $Id: james $
 */

/**
 * @package Hush_Document_Parser
 */
class Hush_Document_Parser_PhpDoc extends Hush_Document_Parser
{
	/**
	 * @var mixed
	 */
	private $_register = array();

	/**
	 * Store data into register
	 * @param string $name
	 * @param string $key
	 * @param mixed $val
	 */
	protected function _setRegister($name, $key, $val = null)
	{
		if ($val) {
			$vName = isset($val[0]) ? trim($val[0]) : '';
			$vDval = isset($val[1]) ? trim($val[1]) : '';
			$vDesc = isset($val[2]) ? trim($val[2]) : '';
			switch ($key) {
				case 'params' :
					$this->_register[$name][$key][$vName] = array(
						'dval' => $vDval,
						'desc' => $vDesc
					);
					break;
				default :
					$this->_register[$name][$key] = $vName;
					break;
			}
		} else {
			$this->_register[$name] = $key;
		}
	}

	/**
	 * Get register by name
	 * @param string $name
	 */
	protected function _getRegister($name)
	{
		return $this->_register[$name];
	}

	/**
	 * Clean register by name
	 * @param string $name
	 */
	protected function _delRegister($name)
	{
		$this->_register[$name] = array();
	}

	/**
	 * Parse annotations for a class file
	 * @param $classFile
	 * @return void
	 */
	public function parseCode($classFile)
	{
		$fp = fopen($classFile, 'r');
		while (!feof($fp)) {
			$codeLine = fgets($fp);
			$this->_parseLine($codeLine);
		}
		fclose($fp);
	}

	/**
	 * Parse each line annotation
	 * @param string $codeLine
	 * @return void
	 */
	protected function _parseLine($codeLine)
	{
		//
		if (preg_match('/@(\w+)\s+(.*?)\s+(.*?)\s+(.*)/i', $codeLine, $annotationRes)) {
			$annotationName = isset($annotationRes[1]) ? trim($annotationRes[1]) : '';
			if ($annotationName) {
				array_shift($annotationRes);
				array_shift($annotationRes);
				$this->_setRegister('annotation', $annotationName, $annotationRes);
			}
		}
		//
		if (preg_match('/class\s+(\w+)\s+/i', $codeLine, $classRes)) {
			$className = isset($classRes[1]) ? trim($classRes[1]) : '';
			if ($className) {
				$this->_setRegister('class', $className);
				$classAnnotation = $this->_getRegister('annotation');
				if ($classAnnotation) {
					$this->_annotation[$className]['_annotation'] = $classAnnotation;
					$this->_delRegister('annotation');
				}
			}
		}
		//
		if (preg_match('/function\s+(\w+)\s+/i', $codeLine, $functionRes)) {
			$functionName = isset($functionRes[1]) ? trim($functionRes[1]) : '';
			if ($functionName) {
				$className = $this->_getRegister('class');
				$functionAnnotation = $this->_getRegister('annotation');
				if ($functionAnnotation) {
					$this->_annotation[$className]['_methodlist'][$functionName]['_annotation'] = $functionAnnotation;
					$this->_delRegister('annotation');
				}
			}
		}
	}
}


text:
#import "SQSDeleteMessageBatchResponseUnmarshaller.h"

@implementation SQSDeleteMessageBatchResponseUnmarshaller

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    [super parser:parser didStartElement:elementName namespaceURI:namespaceURI qualifiedName:qName attributes:attributeDict];

    if ([elementName isEqualToString:@"DeleteMessageBatchResultEntry"]) {
        [parser setDelegate:[[[SQSDeleteMessageBatchResponseEntryUnmarshaller alloc] initWithCaller:self withParentObject:self.response.successful withSetter:@selector(addObject:)] autorelease]];
    }

    if ([elementName isEqualToString:@"BatchResultErrorEntry"]) {
        [parser setDelegate:[[[SQSBatchResponseErrorEntryUnmarshaller alloc] initWithCaller:self withParentObject:self.response.failed withSetter:@selector(addObject:)] autorelease]];
    }

    if ([elementName isEqualToString:@"Error"]) {
        [parser setDelegate:[[[AmazonServiceExceptionUnmarshaller alloc] initWithCaller:self withParentObject:self.response withSetter:@selector(setException:)] autorelease]];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    [super parser:parser didEndElement:elementName namespaceURI:namespaceURI qualifiedName:qName];

    if ([elementName isEqualToString:@"DeleteMessageBatchResult"]) {
        if (caller != nil) {
            [parser setDelegate:caller];
        }

        if (parentObject != nil && [parentObject respondsToSelector:parentSetter]) {
            [parentObject performSelector:parentSetter withObject:self.response];
        }

        return;
    }
}

-(SQSDeleteMessageBatchResponse *)response
{
    if (nil == response) {
        response = [[SQSDeleteMessageBatchResponse alloc] init];
    }
    return response;
}

-(void)dealloc
{
    [response release];
    [super dealloc];
}

@end


text:
package com.brucezee.jspider.samples;

import com.brucezee.jspider.Page;
import com.brucezee.jspider.Request;
import com.brucezee.jspider.Result;
import com.brucezee.jspider.Spider;
import com.brucezee.jspider.processor.PageProcessor;
import org.jsoup.select.Elements;

/**
 * 最简单的爬虫示例
 * Created by brucezee on 2017/9/23.
 */
public class HelloWorldSample {

    public static void main(String[] args) {
        //create, config and start
        Spider.create()                                                 //创建爬虫实例
                .addStartRequests("https://www.baidu.com")           //添加起始url
                .setPageProcessor(new HelloWorldPageProcessor())        //设置页面解析器
                .start();                                               //开始抓取
    }

    public static class HelloWorldPageProcessor implements PageProcessor {
        @Override
        public Result process(Request request, Page page) {
            Result result = new Result();

            //解析HTML采用jsoup框架,详见:https://jsoup.org/

            //解析页面标题
            result.put("title", page.document().title());

            //获取页面上的新的链接地址
            Elements elements = page.document().select("a");        //获取所有a标签
            for (int i = 0; i < elements.size(); i++) {
                String url = elements.get(i).absUrl("href");    //获取绝对url
                if (url != null && url.contains("baidu")) {
                    page.addTargetRequest(url);     //获取新url添加到任务队列
                }
            }

            return result;
        }
    }
}