text:
package com.xem.mzbcustomerapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.xem.mzbcustomerapp.R;
import com.xem.mzbcustomerapp.adapter.SelectXmGroupAdapter;
import com.xem.mzbcustomerapp.base.BaseActivity;
import com.xem.mzbcustomerapp.entity.GroupItem;
import com.xem.mzbcustomerapp.entity.PprojectData;
import com.xem.mzbcustomerapp.net.MzbHttpClient;
import com.xem.mzbcustomerapp.net.MzbUrlFactory;
import com.xem.mzbcustomerapp.net.NetCallBack;
import com.xem.mzbcustomerapp.utils.Config;
import com.xem.mzbcustomerapp.view.MyListView;
import com.xem.mzbcustomerapp.view.TitleBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by xuebing on 15/11/27.
 */
public class B2_SelectXmAty extends BaseActivity {

    @InjectView(R.id.titlebar_iv_left)
    ImageView titlebar_iv_left;
    @InjectView(R.id.listView)
    MyListView listView;
    @InjectView(R.id.subListView)
    MyListView subListView;

    private List<GroupItem> groupItem = new ArrayList<>();
    private List<PprojectData> select_data = new ArrayList<>();

    private int num = 0;

    private GroupItem groupSelected = null;
    private SelectXmGroupAdapter adapter;
    private SelectXmChildAdapter subAdapter;
    private int resultCode = -104;

    @Override
    protected void initView() {
        setContentView(R.layout.b2_selectxm_aty);
        new TitleBuilder(this).setTitleText("选择项目").setLeftImage(R.mipmap.top_view_back);
        ButterKnife.inject(this);
        adapter = new SelectXmGroupAdapter(getApplicationContext(), groupItem);
        listView.setAdapter(adapter);
        adapter.setSelectedPosition(0);
        adapter.notifyDataSetInvalidated();
        Pprjacc();

    }

    @Override
    protected void initData() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetInvalidated();
                final GroupItem cate = groupItem.get(position);
                subAdapter = new SelectXmChildAdapter(getApplicationContext(), cate.getChildren());
                subListView.setAdapter(subAdapter);
                List<PprojectData> pd = cate.getChildren();

                if (pd.size() == 0 && position != 0) {
                    pprojects(position, cate.getPpid(), cate.getCateid());
                }
                groupSelected = cate;
            }
        });

        subListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                PprojectData item = groupSelected.getChildren().get(position);
                item.isSelected = !item.isSelected;
                int i = groupSelected.getSelNum();
                if (item.isSelected) {
                    if (select_data.size() < 5 && i < 5) {
                        select_data.add(item);
                        groupSelected.setSelNum(++i);
                    } else {
                        showToast("预约项目最多不超过5个");
                        item.isSelected = !item.isSelected;
                    }

                } else {
                    select_data.remove(item);
                    groupSelected.setSelNum(--i);
                }
                adapter.notifyDataSetChanged();
                subAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.titlebar_iv_left})
    public void clickAction(View v) {
        switch (v.getId()) {
            case R.id.titlebar_iv_left:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("xm", (Serializable) select_data);
                intent.putExtras(bundle);
                setResult(resultCode, intent);
                finish();
                break;
            default:
                break;
        }
    }

    //获取项目分类
    private void projectCates() {
        RequestParams params = new RequestParams();
        params.put("ppid", Config.getCachedPpid(B2_SelectXmAty.this));

        MzbHttpClient.ClientPost(MzbUrlFactory.BASE_URL + MzbUrlFactory.project_cates, params, new NetCallBack() {
            @Override
            public void onMzbSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONArray jsonArray;
                    if (obj.getInt("code") == 0) {
                        jsonArray = new JSONArray(obj.getString("data"));
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            GroupItem gItem = gson.fromJson(object.toString(), GroupItem.class);
                            groupItem.add(gItem);
                        }
//                        pprojects(0, groupSelected.getPpid(), groupSelected.getCateid());
                        adapter.notifyDataSetChanged();
                    } else {
                        showToast(obj.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("");
            }
        });
    }

    //获取已有项目
    private void Pprjacc() {
        RequestParams params = new RequestParams();
        params.put("ppid", Config.getCachedPpid(B2_SelectXmAty.this));
        params.put("custid", Config.getCachedCustid(B2_SelectXmAty.this));

        MzbHttpClient.ClientPost(MzbUrlFactory.BASE_URL + MzbUrlFactory.prjacc, params, new NetCallBack(this) {
            @Override
            public void onMzbSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONArray jsonArray;
                    if (obj.getInt("code") == 0) {
                        jsonArray = new JSONArray(obj.getString("data"));
                        List<PprojectData> children = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            PprojectData pprojectData = gson.fromJson(object.toString(), PprojectData.class);
                            children.add(pprojectData);
                        }
                        GroupItem group = new GroupItem();
                        group.setName("已有项目");
                        group.setChildren(children);
                        groupItem.add(0, group);
                        groupSelected = groupItem.get(0);
                        projectCates();
                        subAdapter = new SelectXmChildAdapter(getApplicationContext(), children);
                        subListView.setAdapter(subAdapter);
                        subAdapter.notifyDataSetChanged();
                    } else {
                        showToast(obj.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("");
            }
        });
    }

    //获取项目
    private void pprojects(final int position, String ppid, String cateid) {
        RequestParams params = new RequestParams();
        params.put("ppid", ppid);
        params.put("cateid", cateid);
        params.put("begin", 0 + "");
        params.put("count", 20 + "");
        MzbHttpClient.ClientPost(MzbUrlFactory.BASE_URL + MzbUrlFactory.Pprojects, params, new NetCallBack(this) {
            @Override
            public void onMzbSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONArray jsonArray;
                    if (obj.getInt("code") == 0) {
                        jsonArray = new JSONArray(obj.getString("data"));
                        GroupItem group = groupItem.get(position);
                        List<PprojectData> children = group.getChildren();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            PprojectData pprojectData = gson.fromJson(object.toString(), PprojectData.class);
                            children.add(pprojectData);
                        }
                        subAdapter = new SelectXmChildAdapter(getApplicationContext(), children);
                        subListView.setAdapter(subAdapter);
                        subAdapter.notifyDataSetChanged();
                    } else {
                        showToast(obj.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("");
            }
        });
    }

    public class SelectXmChildAdapter extends BaseAdapter {
        Context context;
        LayoutInflater layoutInflater;
        List<PprojectData> subCates;

        public SelectXmChildAdapter(Context context, List<PprojectData> subCates) {
            this.context = context;
            this.subCates = subCates;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public int getCount() {
            return subCates.size();
        }

        @Override
        public Object getItem(int position) {
            return getItem(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.sublist_item, null);
                viewHolder = new ViewHolder();
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textview1);
                viewHolder.img_select = (ImageView) convertView.findViewById(R.id.img_select);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(subCates.get(position).getName());
            viewHolder.textView.setTextColor(Color.BLACK);
            if (select_data.contains(groupSelected.getChildren().get(position))) {
                viewHolder.img_select.setVisibility(View.VISIBLE);
            } else {
                viewHolder.img_select.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

        public class ViewHolder {
            public TextView textView;
            public ImageView img_select;
        }
    }
}


text:
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaebusiness.business import CommandExecutionException
from gaepermission.decorator import login_not_required
from tekton import router
from gaecookie.decorator import no_csrf
from itens_app import itens_facade
from routes import itenss
from tekton.gae.middleware.redirect import RedirectResponse

@login_not_required
@no_csrf
def index(item_id):
    item = itens_facade.get_item_cmd(item_id)()
    item_form = itens_facade.item_form()
    context = {'save_path': router.to_path(save, item_id), 'item': item_form.fill_with_model(item)}
    return TemplateResponse(context, 'itenss/itens_form.html')

@login_not_required
def save(item_id, **item_properties):
    cmd = itens_facade.update_item_cmd(item_id, **item_properties)
    try:
        cmd()
    except CommandExecutionException:
        context = {'errors': cmd.errors, 'item': item_properties}

        return TemplateResponse(context, 'itenss/itens_form.html')
    return RedirectResponse(router.to_path(itenss))

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class Diag::Test < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Diag
  end
end


text:
# load-plugin-resources-host

## set plugin apk

**load-plugin-resource-plugin.apk** add to **assets** of **load-plugin-resource-host module**.

## HOOK

**SmartApplication**

```java
/**
 * @author CaMnter
 */

public class SmartApplication extends Application {

    private DexClassLoader dexClassLoader;

    /**
     * Set the base context for this ContextWrapper.  All calls will then be
     * delegated to the base context.  Throws
     * IllegalStateException if a base context has already been set.
     *
     * @param base The new base context for this wrapper.
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        this.loadDex();
        this.hookInstrumentation();
    }

    private void loadDex() {
        try {
            String dir = null;
            final File cacheDir = this.getExternalCacheDir();
            final File filesDir = this.getExternalFilesDir("");
            if (cacheDir != null) {
                dir = cacheDir.getAbsolutePath();
            } else {
                if (filesDir != null) {
                    dir = filesDir.getAbsolutePath();
                }
            }
            if (TextUtils.isEmpty(dir)) return;

            // assets 的 register-activity-plugin.apk 拷贝到 /storage/sdcard0/Android/data/[package name]/cache
            // 或者  /storage/sdcard0/Android/data/[package name]/files
            final File dexPath = new File(dir + File.separator + "register-activity-plugin.apk");
            AssetsUtils.copyAssets(this, "register-activity-plugin.apk", dexPath.getAbsolutePath());

            // /data/data/[package name]/app_register-activity-plugin
            final File optimizedDirectory = this.getDir("register-activity-plugin", MODE_PRIVATE);

            this.dexClassLoader = new DexClassLoader(
                dexPath.getAbsolutePath(),
                optimizedDirectory.getAbsolutePath(),
                null,
                this.getClassLoader()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hookInstrumentation() {
        try {
            /*
             * 反射 ActivityThread
             * 通过 currentActivityThread 方法
             * 获取存放的 ActivityThread 实例
             */
            @SuppressLint("PrivateApi") final Class<?> activityThreadClass = Class.forName(
                "android.app.ActivityThread");
            final Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(
                "currentActivityThread");
            currentActivityThreadMethod.setAccessible(true);
            final Object currentActivityThread = currentActivityThreadMethod.invoke(null);

            /*
             * ActivityThread 实例获取 Field mInstrumentation
             */
            final Field mInstrumentationField = activityThreadClass.getDeclaredField(
                "mInstrumentation");
            mInstrumentationField.setAccessible(true);
            final Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(
                currentActivityThread);

            // 是否 hook 过
            if (!(mInstrumentation instanceof SmartInstrumentation)) {
                final SmartInstrumentation pluginInstrumentation = new SmartInstrumentation(
                    dexClassLoader, mInstrumentation);
                mInstrumentationField.set(currentActivityThread, pluginInstrumentation);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public DexClassLoader getDexClassLoader() {
        return this.dexClassLoader;
    }

}
```

**SmartInstrumentation**

```java
/**
 * @author CaMnter
 */

public class SmartInstrumentation extends Instrumentation {

    private final ClassLoader classLoader;
    /**
     * 如果不是注册类型的 插件 Activity
     * 需要 hook Instrumentation#execStartActivity 等方法
     * 这个 baseInstrumentation 就会用得着了
     */
    private final Instrumentation baseInstrumentation;

    public SmartInstrumentation(ClassLoader classLoader, Instrumentation baseInstrumentation) {
        this.classLoader = classLoader;
        this.baseInstrumentation = baseInstrumentation;
    }

    /**
     * Perform instantiation of the process's {@link Activity} object.  The
     * default implementation provides the normal system behavior.
     *
     * @param cl The ClassLoader with which to instantiate the object.
     * @param className The name of the class implementing the Activity
     * object.
     * @param intent The Intent object that specified the activity class being
     * instantiated.
     * @return The newly instantiated Activity object.
     */
    @Override
    public Activity newActivity(ClassLoader cl, String className, Intent intent)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        //  hook 结果 其他 dex 中,相同 className 的 Activity
        return super.newActivity(this.classLoader, className, intent);
    }

}
```


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

import { IsoDateValueAccessor } from './iso-date-value-accessor';
import { Context, dispatchInputEvent, setupTemplateDrivenForms } from './spec-utils';

@Component({
  template: `
  <form>
    <input type="date" [(ngModel)]="testDate" name="someName" useValueAsIso>
  </form>`
})
export class TestFormComponent {
  testDate = new Date('2020-01-01').toISOString(); // Create UTC Date
}

describe('IsoDateValueAccessor (template-driven forms)', () => {

  let c: Context<TestFormComponent> = {};
  setupTemplateDrivenForms(c, TestFormComponent, IsoDateValueAccessor);

  it('should reflect changes from the model to the input after init', () => {
    expect(c.inputElement.value).toBe('2020-01-01');
  });

  it('should reflect changes from the model to the input', done => {
    c.fixture.componentInstance.testDate = new Date('2021-11-15').toISOString();
    c.fixture.detectChanges();
    c.fixture.whenStable().then(() => {
      expect(c.inputElement.value).toBe('2021-11-15');
      done();
    })
  });

  it('should reflect changes from the input to the model', () => {
    dispatchInputEvent(c.inputElement, '2020-12-31');
    expect(c.fixture.componentInstance.testDate).toBe('2020-12-31T00:00:00.000Z');
  });

  it('should populate NULL for invalid dates', () => {
    dispatchInputEvent(c.inputElement, "NOT A DATE");
    expect(c.fixture.componentInstance.testDate).toBeNull();
    expect(c.inputElement.value).toBe('');
  });
});


text:
#import <PhysicsKit/PKPhysicsBody.h>

@interface PKPhysicsBody (Internal)
@property(nonatomic) struct b2Body *_body;
@property(nonatomic) struct b2BodyDef _bodyDef;
- (void)set_inUse:(_Bool)arg1;
- (_Bool)_inUse;
- (void)set_joints:(id)arg1;
- (id)_joints;
- (id)_world;
- (void)set_world:(id)arg1;
@property(nonatomic) struct b2FixtureDef _fixtureDef;
@property(nonatomic) struct b2Fixture *_fixture;
- (void)setActive:(_Bool)arg1;
- (_Bool)active;
- (_Bool)isSensor;
- (void)setIsSensor:(_Bool)arg1;
@end


text: export { StopFilled as default } from "./";


text:
pynq.lib Package
================

pynq.lib contains the arduino, pmod, and logictools subpackages, and additional
modules for communicating with other controllers in an overlay.

Modules:
  * :mod:`pynq.lib.audio` - Implements mono-mode audio driver using pulse density modulation (PDM)
  * :mod:`pynq.lib.axigpio` - Implements driver for AXI GPIO IP
  * :mod:`pynq.lib.button` - Implements driver for AXI GPIO push button IP
  * :mod:`pynq.lib.cmac` - Implements driver for UltraScale+ Integrated 100G Ethernet Subsystem
  * :mod:`pynq.lib.dma` - Implements driver for the AXI Direct Memory Access (DMA) IP
  * :mod:`pynq.lib.iic` - Implements driver for AXI IIC IP
  * :mod:`pynq.lib.led` - Implements driver for AXI GPIO LED IP
  * :mod:`pynq.lib.pynqmicroblaze.pynqmicroblaze` - Implements communcation and control for a PYNQ MicroBlaze subsystem
  * :mod:`pynq.lib.rgbled` - Implements driver for AXI GPIO multi color LEDs
  * :mod:`pynq.lib.switch` - Implements driver for AXI GPIO Dual In-Line (DIP) switches
  * :mod:`pynq.lib.video` - Implements driver for HDMI video input/output
  * :mod:`pynq.lib.wifi` - Implements driver for WiFi

Subpackages:
  * :ref:`pynq-lib-arduino`- Implements driver for Arduino IO Processor Subsystem
  * :ref:`pynq-lib-pmod` - Implements driver for PMOD IO Processor Subsystem
  * :ref:`pynq-lib-logictools` - Implements driver for Logictools IP Processor Subsystem
  * :ref:`pynq-lib-rpi` - Implements driver for Raspberry Pi IO Processor Subsystem

.. toctree::
    :hidden:

    pynq.lib/pynq.lib.arduino
    pynq.lib/pynq.lib.audio
    pynq.lib/pynq.lib.axigpio
    pynq.lib/pynq.lib.button
    pynq.lib/pynq.lib.cmac
    pynq.lib/pynq.lib.dma
    pynq.lib/pynq.lib.iic
    pynq.lib/pynq.lib.led
    pynq.lib/pynq.lib.logictools
    pynq.lib/pynq.lib.pmod
    pynq.lib/pynq.lib.pynqmicroblaze
    pynq.lib/pynq.lib.rgbled
    pynq.lib/pynq.lib.rpi
    pynq.lib/pynq.lib.switch
    pynq.lib/pynq.lib.video
    pynq.lib/pynq.lib.wifi


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace PeoplePickerRemediation.Console.Common.Utilities
{
    public static class CommonUtility
    {

        /// <summary>
        // Excel/CSV Cell CharacterLimit. According to Microsoft's documentation:
        // https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3
        // Excel cannot read more than 32767 characters in a single cell
        // Total number of characters that a cell can contain: 32,767 characters
        // This function checks if the value of a column is more than 32,767 characters, and if it finds any it splits the data into rows so as to save it in csv/excel
        /// </summary>
        /// <param name="stringToSplit"></param>
        /// <returns></returns>
        public static IEnumerable<string> SplitToLines(string stringToSplit)
        {
            stringToSplit = stringToSplit.Trim();
            var lines = new List<string>();

            //If stringToSplit is Blank then return Constants.NotApplicable
            if (stringToSplit.Length != 0)
            {
                while (stringToSplit.Length > 0)
                {
                    if (stringToSplit.Length <= Constants.CharacterLimitForCsvCell)
                    {
                        lines.Add(stringToSplit);
                        break;
                    }

                    int indexOfLastSpaceInLine = stringToSplit.Substring(0, Constants.CharacterLimitForCsvCell).LastIndexOf(' ');

                    lines.Add(stringToSplit.Substring(0, indexOfLastSpaceInLine >= 0 ? indexOfLastSpaceInLine : Constants.CharacterLimitForCsvCell).Trim());

                    stringToSplit = stringToSplit.Substring(indexOfLastSpaceInLine >= 0 ? indexOfLastSpaceInLine + 1 : Constants.CharacterLimitForCsvCell);
                }
            }
            else
            {
                //If stringToSplit is Blank then return Constants.NotApplicable
                lines.Add(Constants.NotApplicable);
            }

            return lines.ToArray();
        }

        /// <summary>
        /// Returns a string Url by combining the WebAplicationUrl and the Input Url (Which Can be - SiteCollectionUrl, WebUrl and PageUrl)
        /// </summary>
        /// <param name="WebApplicationUrl"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetUrl(string WebApplicationUrl, string Url)
        {
            string newUrl = string.Empty;

            if (WebApplicationUrl.EndsWith("/"))
            {
                if (Url.StartsWith("/"))
                    newUrl = Regex.Match(WebApplicationUrl, "^(.*).{1}", RegexOptions.IgnoreCase).Groups[1].Value + Url;
                else
                    newUrl = WebApplicationUrl + Url;
            }
            else if (Url.StartsWith("/"))
                newUrl = WebApplicationUrl + Url;
            else
                newUrl = WebApplicationUrl + "/" + Url;

            return newUrl;
        }
    }
}


text:
package org.apache.camel.component.jdbc.aggregationrepository;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JdbcAggregateRecoverWithSedaTest extends CamelTestSupport {

    private static AtomicInteger counter = new AtomicInteger(0);
    private JdbcAggregationRepository repo;

    @Override
    public void setUp() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/component/jdbc/aggregationrepository/JdbcSpringDataSource.xml");
        repo = applicationContext.getBean("repo1", JdbcAggregationRepository.class);
        // enable recovery
        repo.setUseRecovery(true);
        // check faster
        repo.setRecoveryInterval(500, TimeUnit.MILLISECONDS);

        super.setUp();
    }

    @Test
    public void testJdbcAggregateRecoverWithSeda() throws Exception {
        // should fail the first 2 times and then recover
        getMockEndpoint("mock:aggregated").expectedMessageCount(3);
        getMockEndpoint("mock:result").expectedBodiesReceived("ABCDE");
        // should be marked as redelivered
        getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERED).isEqualTo(Boolean.TRUE);
        // on the 2nd redelivery attempt we success
        getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERY_COUNTER).isEqualTo(2);

        template.sendBodyAndHeader("direct:start", "A", "id", 123);
        template.sendBodyAndHeader("direct:start", "B", "id", 123);
        template.sendBodyAndHeader("direct:start", "C", "id", 123);
        template.sendBodyAndHeader("direct:start", "D", "id", 123);
        template.sendBodyAndHeader("direct:start", "E", "id", 123);

        assertMockEndpointsSatisfied(30, TimeUnit.SECONDS);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .aggregate(header("id"), new MyAggregationStrategy())
                        .completionSize(5).aggregationRepository(repo)
                        .log("aggregated exchange id ${exchangeId} with ${body}")
                        .to("mock:aggregated")
                        .to("seda:foo")
                        .end();

                // should be able to recover when we send over SEDA as its a OnCompletion
                // which confirms the exchange when its complete.
                from("seda:foo")
                        .delay(1000)
                                // simulate errors the first two times
                        .process(new Processor() {
                            public void process(Exchange exchange) throws Exception {
                                int count = counter.incrementAndGet();
                                if (count <= 2) {
                                    throw new IllegalArgumentException("Damn");
                                }
                            }
                        })
                        .to("mock:result");
            }
        };
    }

    public static class MyAggregationStrategy implements AggregationStrategy {

        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                return newExchange;
            }
            String body1 = oldExchange.getIn().getBody(String.class);
            String body2 = newExchange.getIn().getBody(String.class);

            oldExchange.getIn().setBody(body1 + body2);
            return oldExchange;
        }
    }
}


text:
module OodAppkit
  module DefaultCookieOptions
    def handle_options(options)
      if base_uri = ENV["RAILS_RELATIVE_URL_ROOT"]
        options[:path] = base_uri unless /^#{Regexp.quote base_uri}/ =~ options[:path]
      end
      super(options)
    end
  end
end

ActionDispatch::Cookies::CookieJar.prepend OodAppkit::DefaultCookieOptions


text:
#include "../x11.h"

ulong
getproperty(Window *w, char *prop, char *type, Atom *actual,
	    ulong offset, uchar **ret, ulong length) {
	int format;

	return getprop(w, prop, type, actual, &format, offset, ret, length);
}


text:
#ifndef TI_TIUISCROLLVIEW_H_
#define TI_TIUISCROLLVIEW_H_

#include <TiCore.h>
#include "ScrollViewContentViewProxy.h"

namespace bb
{
namespace cascades
{
class ScrollView;
}
}
namespace TiUI {

class TiUIScrollView : public Ti::TiView
{
	Q_OBJECT;
public:
	TiUIScrollView(Ti::TiViewProxy*);
	virtual ~TiUIScrollView();

	virtual bool ingoreWidth();
	virtual bool ingoreHeight();
	virtual QString defaultWidth();
	virtual QString defaultHeight();
	virtual void onTapEvent(bb::cascades::TapEvent*);

	virtual void onRelayout(QRectF);
	void setLayout(QString);
	void setContentSize(QSizeF);
	bb::cascades::ScrollView* getScrollView();
	Ti::TiView * getInnerView();
	Ti::TiViewProxy *getInnerViewProxy();
	void updateContentSize(QRectF);
	void setScrollEvent();
	QString _contentWidth;
	QString _contentHeight;
private:
	Ti::TiView *_innerView;
	Ti::TiViewProxy *_innerViewProxy;
	bb::cascades::ScrollView* _scrollView;
	QSizeF _contentSize;
	QSizeF _viewSize;
	bool _hasScrollEvent;
public slots:
	void onScroll(const QRectF&, float);
};
}
#endif /* TIUISCROLLVIEW_H_ */


text:
Dir[File.join(File.expand_path("jekyll", __dir__), "*.rb")].each do |ruby_file|
  require ruby_file
end


text:
local overfull = 1073741820
local inf_bad = 10000
local eject_penalty = -inf_bad
local deplorable = 100000   --  worse than inifinitely bad!

local tcpb = {}

--! is something special needed for eject penalty?

-- Look at all the material left..#oq.
-- Find 'best' place into two columns that fit on current page.
-- Return right, rightEnd, penalty.
-- Penalty will be ovefull if there is no way to fit anything on page.
function tcpb.findBestTwoColBreak(oq, left, targetHeight)
  assert(left >= 1 and left <= #oq)
  if SILE.debugFlags.twocol then
    print("findBestTwoColBreak left="..left..","..
      "targetHeight="..targetHeight..", ("..#oq..")")
    for i=left,#oq do
      print(i, oq[i])
    end
  end

  local right, rightEnd, penalty = nil, nil, overfull  -- outputs
  local _right, _rightEnd, _penalty, _height

  for _right=left+1,#oq+1 do
    if _right == #oq+1 or oq[_right]:isVbox() then
      local _rightEnd, _penalty, _height = tcpb.findBestTwoColBreak2(
                                     oq, left, _right, targetHeight)
      if _height > targetHeight then break end
      if _rightEnd and _penalty <= penalty then
        right, rightEnd, penalty = _right, _rightEnd, _penalty
      end
    end
  end

  SU.debug("twocol",
    "   ****** right="..right..", rightEnd="..rightEnd..", penalty="..penalty)
  return right, rightEnd, penalty
end

-- warning! right may be as large as #oq+1
-- returns rightEnd, penalty, height
function tcpb.findBestTwoColBreak2(oq, left, right, targetHeight)
  SU.debug("twocol",
     "   findBestTwoColBreak2 left="..left..
     ", right="..right..", targetHeight="..targetHeight)
  local rightEnd, penalty, leftHeight = nil, overfull, nil   -- outputs

  leftHeight = tcpb.columnHeight(oq, left, right)
  if leftHeight > targetHeight then return rightEnd, penalty, leftHeight end
  local leftPenalty = tcpb.columnPenalty(oq, right)

  for _rightEnd=right,#oq+1 do
    if _rightEnd == #oq+1 or oq[_rightEnd]:isVbox() then
      local rightHeight = tcpb.columnHeight(oq, right, _rightEnd)
      if rightHeight > leftHeight then
          SU.debug("twocol", "         rightHeight > leftHeight")
        break
      end

      local rightPenalty = tcpb.columnPenalty(oq, _rightEnd)
      local pageBottomGap = targetHeight - leftHeight
      local interColumnGap = leftHeight - rightHeight
      local remainingLines = tcpb.countLines(oq, _rightEnd)
      local _penalty = tcpb.calculatePenalty(leftPenalty, rightPenalty,
                         pageBottomGap, interColumnGap, remainingLines)

      SU.debug("twocol", "         *** ".._penalty.." "..right.."/".._rightEnd)
      if _rightEnd and _penalty <= penalty then
        rightEnd, penalty = _rightEnd, _penalty
      end
    end
  end

  SU.debug("twocol", "      *** ", penalty.." "..right.."/"..rightEnd..", h="..leftHeight)
  return rightEnd, penalty, leftHeight
end

function tcpb.countLines(oq, first)
  local count = 0
  for i=first,#oq do
    if oq[i]:isVbox() then count = count+1 end
  end
  return count
end

-- return penalty
function tcpb.calculatePenalty(leftPenalty, rightPenalty, pageBottomGap, interColumnGap, remainingLines)
  local penalty
  if leftPenalty > 100 or rightPenalty > 100 then
    penalty = overfull
  else
    penalty = pageBottomGap.length + interColumnGap.length + 1000*remainingLines
  end

  return penalty
end

function tcpb.columnHeight(oq, first, last)
  local h = SILE.length.new({})

  local i
  for i=first,last-1 do
    h = h + oq[i].height + oq[i].depth
  end

  return h
end

-- return height, penalty
function tcpb.columnPenalty(oq, last)
  local p = 0
  last = last-1
  while last >= 1 and oq[last]:isVglue() do last = last-1 end
  if last >= 1 and oq[last]:isPenalty() then p = oq[last].penalty end

  return p
end

return tcpb


text:
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope="member", Target="System.ComponentModel.ListChangedEventArgs..ctor(System.ComponentModel.ListChangedType,System.Int32,System.ComponentModel.PropertyDescriptor)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope="member", Target="System.ComponentModel.ListChangedEventArgs..ctor(System.ComponentModel.ListChangedType,System.ComponentModel.PropertyDescriptor)")]

namespace System.ComponentModel {

    using Microsoft.Win32;
    using System;
    using System.Diagnostics;
    using System.Security.Permissions;

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    [HostProtection(SharedState = true)]
    public class ListChangedEventArgs : EventArgs {

        private ListChangedType listChangedType;
        private int newIndex;
        private int oldIndex;
        private PropertyDescriptor propDesc;

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public ListChangedEventArgs(ListChangedType listChangedType, int newIndex) : this(listChangedType, newIndex, -1) {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public ListChangedEventArgs(ListChangedType listChangedType, int newIndex, PropertyDescriptor propDesc) : this(listChangedType, newIndex) {
            this.propDesc = propDesc;
            this.oldIndex = newIndex;
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public ListChangedEventArgs(ListChangedType listChangedType, PropertyDescriptor propDesc) {
            Debug.Assert(listChangedType != ListChangedType.Reset, "this constructor is used only for changes in the list MetaData");
            Debug.Assert(listChangedType != ListChangedType.ItemAdded, "this constructor is used only for changes in the list MetaData");
            Debug.Assert(listChangedType != ListChangedType.ItemDeleted, "this constructor is used only for changes in the list MetaData");
            Debug.Assert(listChangedType != ListChangedType.ItemChanged, "this constructor is used only for changes in the list MetaData");

            this.listChangedType = listChangedType;
            this.propDesc = propDesc;
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public ListChangedEventArgs(ListChangedType listChangedType, int newIndex, int oldIndex) {
            Debug.Assert(listChangedType != ListChangedType.PropertyDescriptorAdded, "this constructor is used only for item changed in the list");
            Debug.Assert(listChangedType != ListChangedType.PropertyDescriptorDeleted, "this constructor is used only for item changed in the list");
            Debug.Assert(listChangedType != ListChangedType.PropertyDescriptorChanged, "this constructor is used only for item changed in the list");
            this.listChangedType = listChangedType;
            this.newIndex = newIndex;
            this.oldIndex = oldIndex;
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public ListChangedType ListChangedType {
            get {
                return listChangedType;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public int NewIndex {
            get {
                return newIndex;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public int OldIndex {
            get {
                return oldIndex;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public PropertyDescriptor PropertyDescriptor {
            get {
                return propDesc;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center_vertical"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              android:paddingBottom="@dimen/activity_vertical_margin" >

    <Button
        android:text="@string/record_user_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button29"
        android:onClick="onClickUserData01"/>

    <Button
        android:text="@string/custom_modifiers_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button30"
        android:onClick="onClickUserData02"/>

    <Button
        android:text="@string/custom_modifiers_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button31"
        android:onClick="onClickUserData03"/>

    <Button
        android:text="@string/user_logged_in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button32"
        android:onClick="onClickUserData04"
        android:enabled="false"/>

    <Button
        android:text="@string/user_logged_out"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button33"
        android:onClick="onClickUserData05"
        android:enabled="false"/>
</LinearLayout>


text:
package agh.edu.model.viewable;

import agh.edu.model.FoodInfo;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class ViewableFoodInfo {
    private final StringProperty name;
    private final DoubleProperty kcal;
    private final DoubleProperty prot;
    private final DoubleProperty carbs;
    private final DoubleProperty fat;

    public ViewableFoodInfo(String name, double kcal, double prot, double carbs, double fat) {
        this.name = new SimpleStringProperty(name);
        this.kcal = new SimpleDoubleProperty(kcal);
        this.prot = new SimpleDoubleProperty(prot);
        this.carbs = new SimpleDoubleProperty(carbs);
        this.fat = new SimpleDoubleProperty(fat);
    }

    public static ViewableFoodInfo fromFoodInfo(FoodInfo foodInfo) {
        return new ViewableFoodInfo(foodInfo.getName(), foodInfo.getKcal(), foodInfo.getProtein(), foodInfo.getCarbs(), foodInfo.getFat());
    }

    public String getName() { return name.get();}
    public double getKcal() { return kcal.get();}
    public double getProt() { return prot.get();}
    public double getCarbs() { return carbs.get();}
    public double getFat() { return  fat.get();}
}


text:
package co.phoenixlab.dds;

import ar.com.hjg.pngj.ImageInfo;
import ar.com.hjg.pngj.ImageLineHelper;
import ar.com.hjg.pngj.ImageLineInt;
import ar.com.hjg.pngj.PngWriter;
import co.phoenixlab.dds.decoder.Decoders;
import co.phoenixlab.dds.decoder.FormatDecoder;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntUnaryOperator;

public class DdsImageDecoder {

    private static final Map<String, IntUnaryOperator> SWIZZLER_CACHE = new HashMap<>();

    private static final IntUnaryOperator GET_RED = i -> i >> 16 & 255;
    private static final IntUnaryOperator GET_GREEN = i -> i >> 8 & 255;
    private static final IntUnaryOperator GET_BLUE = i -> i & 255;
    private static final IntUnaryOperator GET_ALPHA = i -> i >> 24 & 255;
    private static final IntUnaryOperator GET_MIN = i -> 0;
    private static final IntUnaryOperator GET_MAX = i -> 255;
    private static final IntUnaryOperator NEGATE = i -> 255 - i;

    private static final IntUnaryOperator SET_RED = i -> (i & 255) << 16;
    private static final IntUnaryOperator SET_GREEN = i -> (i & 255) << 8;
    private static final IntUnaryOperator SET_BLUE = i -> i & 255;
    private static final IntUnaryOperator SET_ALPHA = i -> (i & 255) << 24;

    private static final IntUnaryOperator[] SETTERS = new IntUnaryOperator[]{
        SET_RED,
        SET_GREEN,
        SET_BLUE,
        SET_ALPHA
    };

    public DdsImageDecoder() {

    }

    private static IntUnaryOperator buildSwizzler(String swizzle) {
        if (swizzle.length() != 4) {
            if (swizzle.length() == 3) {
                //  Assume alpha of 1 if not specified
                swizzle = swizzle + "1";
            } else {
                throw new IllegalArgumentException("Invalid swizzle string (bad length)");
            }
        }
        char[] chars = swizzle.toCharArray();

        IntUnaryOperator[] ops = new IntUnaryOperator[4];

        for (int i = 0; i < 4; i++) {
            ops[i] = getSourceOp(chars[i]).andThen(SETTERS[i]);
        }

        return i -> {
            int ret = 0;
            ret |= ops[0].applyAsInt(i);
            ret |= ops[1].applyAsInt(i);
            ret |= ops[2].applyAsInt(i);
            ret |= ops[3].applyAsInt(i);
            return ret;
        };
    }

    private static IntUnaryOperator getSourceOp(char c) {
        switch (c) {
            case 'r':
            case 'x':
                return GET_RED;
            case 'R':
            case 'X':
                return GET_RED.andThen(NEGATE);
            case 'g':
            case 'y':
                return GET_GREEN;
            case 'G':
            case 'Y':
                return GET_GREEN.andThen(NEGATE);
            case 'b':
            case 'z':
                return GET_BLUE;
            case 'B':
            case 'Z':
                return GET_BLUE.andThen(NEGATE);
            case 'a':
            case 'w':
                return GET_ALPHA;
            case 'A':
            case 'W':
                return GET_ALPHA.andThen(NEGATE);
            case '0':
                return GET_MIN;
            case '1':
                return GET_MAX;
            default:
                throw new IllegalArgumentException("Invalid swizzle value");
        }
    }

    public byte[] convertToRawARGB8(Dds dds) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            convertToRawARGB8(dds, byteArrayOutputStream);
        } catch (IOException e) {
            //  Impossible
        }

        return byteArrayOutputStream.toByteArray();
    }

    public void convertToRawARGB8(Dds dds, OutputStream outputStream) throws IOException {
        DataOutputStream dataOutputStream;
        if (outputStream instanceof DataOutputStream) {
            dataOutputStream = (DataOutputStream) outputStream;
        } else {
            dataOutputStream = new DataOutputStream(outputStream);
        }

        FormatDecoder decoder = Decoders.getDecoder(dds);
        for (int[] ints : decoder) {
            for (int pixel : ints) {
                dataOutputStream.writeInt(pixel);
            }
        }

        outputStream.flush();
    }

    public byte[] convertToPNG(Dds dds) {
        return convertToPNG(dds, "");
    }

    public byte[] convertToPNG(Dds dds, String swizzle) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            convertToPNG(dds, byteArrayOutputStream, swizzle);
        } catch (IOException e) {
            //  Impossible
        }

        return byteArrayOutputStream.toByteArray();
    }

    public void convertToPNG(Dds dds, OutputStream outputStream) throws IOException {
        convertToPNG(dds, outputStream, "");
    }

    public void convertToPNG(Dds dds, OutputStream outputStream, String swizzle) throws IOException {
        DdsHeader header = dds.getHeader();
        FormatDecoder decoder = Decoders.getDecoder(dds);
        ImageInfo imageInfo = new ImageInfo(header.getDwWidth(), header.getDwHeight(), 8, true);
        PngWriter pngWriter = new PngWriter(outputStream, imageInfo);
        ImageLineInt imageLine = new ImageLineInt(imageInfo);
        for (int[] ints : decoder) {
            swizzle(ints, swizzle);
            ImageLineHelper.setPixelsRGBA8(imageLine, ints);
            pngWriter.writeRow(imageLine);
        }

        pngWriter.end();
    }

    private void swizzle(int[] ints, String swizzle) {
        if (swizzle.isEmpty()) {
            return;
        }

        //  Build swizzler
        IntUnaryOperator swizzler = SWIZZLER_CACHE.computeIfAbsent(swizzle, DdsImageDecoder::buildSwizzler);

        //  Apply
        for (int i = 0; i < ints.length; i++) {
            ints[i] = swizzler.applyAsInt(ints[i]);
        }
    }

}


text:
class AddCrawlerToDeals < ActiveRecord::Migration[5.0]
  def change
    add_column :deals, :crawler, :integer
  end
end


text:
package N2Configuration.api.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.Logger;

import N2Configuration.api.N2ConfigApi;

/**
 * @author N247S
 * An ingame Config Manager
 */

public final class ConfigHandler
{
	private static HashMap<ConfigFile, File> fileList = new HashMap<ConfigFile, File>();
	private static Logger log = N2ConfigApi.log;

	public enum FileType
	{
		Original,
		BackUp,
		/**
		 * Don't use this until its really an temporary file!, otherwise use backup or clone instead!
		 */
		Temp,
		Clone,
	}

	/**
	 * This will register a ConfigurationFile. (.cfg)
	 * Note, when creating a new ConfigFile, it will automatically register itself!
	 * @param configFile
	 * @param fileName - This is the name what the ConfigFile will have. (fileName.cfg)
	 * @param targetDirectory - This is the Directory where the ConfigFile will go.
	 * 	If you want it to be in the default configDir, use "N2ConfigAPI.getConfigDir()"
	 */
	protected static void registerConfigurationFile(ConfigFile configFile, String fileName, File targetDirectory)
	{
		if(N2ConfigApi.DirectoryList.isEmpty())
		{
			File defaultFile = new File(N2ConfigApi.getMCMainDir(), "config");
			N2ConfigApi.DirectoryList.put("Default", defaultFile);
			N2ConfigApi.TempDirectoryList.put(defaultFile, (new File(N2ConfigApi.getConfigDir(), "temp")));
		}
		File newFile;
		if(targetDirectory.isDirectory())
			newFile = new File(targetDirectory, (fileName += ".cfg"));
		else newFile = new File(N2ConfigApi.getConfigDir(), (fileName += ".cfg"));

		Iterator file = fileList.keySet().iterator();

		while(file.hasNext())
		{
			File currentFile = (File) fileList.get(file.next());
			if(currentFile.getName() == fileName)
				throw new IllegalArgumentException("Filename " + fileName + " already exist!");
		}

		if(configFile != null)
			if(!fileList.containsKey(configFile))
				fileList.put(configFile, newFile);
			else
				log.warn("ConfigurationFile is already registered!");
		else throw new NullPointerException();
	}

	/**
	 * @param fileName
	 * @return true if the ConfigFile is removed, false otherwise.
	 */
	public static boolean removeConfigurationFile(String fileName)
	{
		ConfigFile configFile = getConfigFileFromName(fileName);

		if(configFile == null || !InitConfigObject.removeConfigFile(fileName))
			return false;

		fileList.remove(getConfigFileFromName(fileName));
		return true;
	}

	/**
	 * This will create new, or check all existing files.
	 * Warning!, you really shouldn't call this if you don't know what you are doing!
	 * (Inaccessible for now, since there isn't a way to store files per ModInstance,
	 * this would only harm the performance when called.)
	 */
	private static void loadAndCheckAllConfigFiles()
	{
		try
		{
			Iterator DirectoryID = N2ConfigApi.DirectoryList.keySet().iterator();
			while(DirectoryID.hasNext())
			{
				File dir = N2ConfigApi.DirectoryList.get(DirectoryID.next());
				dir.mkdirs();
			}
			generateAllFiles();
			Iterator<ConfigFile> file = fileList.keySet().iterator();
			while(file.hasNext())
			{
				ConfigFile current = file.next();
				List<String> invalidSections = current.checkConfigFile();
				if(invalidSections != null)
					current.regenerateConfigFile(invalidSections);
				current.saveConfigValues();
			}
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	/**
	 * This will create or check the configFile.
	 * @param configFileName
	 */
	public static void loadAndCheckConfigFile(String configFileName)
	{
		try
		{
			ConfigFile configFile = getConfigFileFromName(configFileName);
			if(configFile != null)
			{
				generateSingleFile(configFile);

				List<String> invalidSections = configFile.checkConfigFile();
				configFile.regenerateConfigFile(invalidSections);
				configFile.saveConfigValues();
			}
			else log.error("Couldn't find ConfigFile: " + configFileName);
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	/**
	 * This will create the configFile.
	 * @param configFileName
	 */
	public static void loadConfigFile(String configFileName)
	{
		try
		{
			ConfigFile configFile = getConfigFileFromName(configFileName);
			if(configFile == null)
				log.error("Couldn't find ConfigFile: " + configFileName);
			else
			{
				generateSingleFile(configFile);
				configFile.saveConfigValues();
			}
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	/**
	 * This will create or check all the configFiles in the StringArray.
	 * @param configFileNames
	 */
	public static void loadAndCheckConfigFileList(String[] configFileNames)
	{
		try
		{
			for(int i = 0; i < configFileNames.length; i++)
			{
				loadAndCheckConfigFile(configFileNames[i]);
			}
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	/**
	 * This will create all the configFiles in the StringArray.
	 * @param configFileNames
	 */
	public static void loadConfigFileList(String[] configFileNames)
	{
		try
		{
			for(int i = 0; i < configFileNames.length; i++)
			{
				ConfigFile configFile = getConfigFileFromName(configFileNames[i]);
				if(configFile == null)
					log.error("Couldn't find ConfigFile: " + configFileNames[i]);
				else
				{
					generateSingleFile(configFile);
					configFile.saveConfigValues();
				}
			}
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	/**
	 * This will create a single File. Note, if an File already exist, it will be overwritten! (except 'Clone' FileTypes)
	 * @param originalFileName - Don't include the FileExtension!
	 * @param extension
	 * @param fileType
	 * @param originalFile
	 * @param targetDirectory - The Directory where this File will be created
	 * @return - The new created File. Note, the 'original' fileType will return an empty File!
	 * @throws IOException
	 */
	public static File generateSingeFile(String originalFileName, FileType fileType, File originalFile, File targetDirectory) throws IOException
	{
		File target = null;
		if(targetDirectory != null)
			if(targetDirectory.isDirectory())
				target = targetDirectory;
			else log.error("File isn't generated. Couldn't resolve targetDirectory!");

		File newFile = null;

		switch(fileType)
		{
		case Original:
			newFile = originalFile;
			break;
		case BackUp:
			newFile = new File(target, originalFileName + "_BackUp.txt");
			break;
		case Temp:
			newFile = new File(target, originalFileName + "_Temp.tmp");
			break;
		case Clone:
			int i = 1;
			if(ConfigHandler.getConfigFileFromName(originalFileName) == null)
				newFile = new File(target, originalFileName);
			else
			{
				while(true)
				{
					newFile = new File(target, originalFileName + "_copy_" + i + originalFile.getName().substring(originalFileName.length(), originalFile.getName().length()));
					if(newFile.exists()) i++;
					else break;
				}
			}
			break;
		}
		if(newFile.exists())
			newFile.delete();
		newFile.createNewFile();
		if(fileType != FileType.Original)
			copyFile(originalFile, newFile);
		return newFile;
	}

	/**
	 * This will create a new ConfigFile. Note, it will override existing files (except 'Clone' FileTypes).
	 * @param fileType
	 * @param configFile
	 * @param targetDirectory - This is the Directory where the ConfigurationFile will be created.
	 * @return - The new created File. Note, the 'original' fileType will return an empty File!
	 * @throws IOException
	 */
	public static File generateSingleFileFromConfigFile(ConfigFile configFile, FileType fileType, File targetDirectory) throws IOException
	{
		return generateSingleFileFromConfigFile(null, configFile, fileType, targetDirectory);
	}

	/**
	 * This is mainly used for Clones with specific names.
	 * @param fileName
	 * @param fileType
	 * @param configFile
	 * @param targetDirectory - This is the Directory where the ConfigurationFile will be created.
	 * @return - The new created File. Note, the 'original' fileType will return an empty File!
	 * @throws IOException
	 */
	public static File generateSingleFileFromConfigFile(String fileName, ConfigFile configFile, FileType fileType, File targetDirectory)
	{
		File target = null;
		if(targetDirectory == null)
			target = getFileFromConfigFile(configFile).getParentFile();
		else target = targetDirectory;
		String originalFileName = configFile.getFileName();
		File originalFile = fileList.get(configFile);

		File file = null;
		ConfigFile newConfigurationFile = null;

		try
		{
			if(fileName != null)
				file = generateSingeFile(fileName, FileType.Original, originalFile, targetDirectory);
			else file = generateSingeFile(originalFileName, fileType, originalFile, targetDirectory);
		}
		catch(Exception e)
		{
			log.catching(e);
		}

		if(fileType.equals(FileType.Clone))
		{
			try
			{
				newConfigurationFile = (ConfigFile) configFile.CloneConfigurationFileInstance();
			}
			catch(Exception e)
			{
				log.catching(e);
			}

			if(fileName != null)
				newConfigurationFile.setFileName(fileName);
			else newConfigurationFile.setFileName(file.getName().substring(0, file.getName().length()-4));

			if(fileName != null)
				registerConfigurationFile(newConfigurationFile, fileName, targetDirectory);
			else registerConfigurationFile(newConfigurationFile, file.getName().substring(0, file.getName().length()-4), targetDirectory);
		}
		newConfigurationFile.saveConfigValues();
		return file;
	}

	/**
	 * Don't, just don't!
	 * @throws IOException
	 */
	private static void generateAllFiles() throws IOException
	{
		Iterator i = fileList.keySet().iterator();

		while(i.hasNext())
		{
			ConfigFile currentConfigFile = (ConfigFile) i.next();
			if(currentConfigFile != null)
				{
				File file = getFileFromConfigFile(currentConfigFile);
				File dir = file.getParentFile();
				File dirtemp = N2ConfigApi.getTempDir(dir);

				dir.mkdirs();
				dirtemp.mkdirs();
				if(!file.exists())
					file.createNewFile();

				currentConfigFile.generateFile();

				if(!currentConfigFile.getIsWritten())
					currentConfigFile.writeAllSections();
			}
		}
	}

	private static void generateSingleFile(ConfigFile configFile) throws IOException
	{
		if(configFile != null)
		{
			File file = getFileFromConfigFile(configFile);
			File dir = file.getParentFile();
			File dirtemp = N2ConfigApi.getTempDir(dir);

			dir.mkdirs();
			dirtemp.mkdirs();
			if(!file.exists())
				file.createNewFile();

			configFile.generateFile();

			if(!configFile.getIsWritten())
				configFile.writeAllSections();
		}
	}

	/**
	 * This will simply copy the content of one File, into the other.
	 * @param oldFile - File which you want to copy from.
	 * @param copyFile - File which it should copy to.
	 * @throws IOException
	 */
	public static void copyFile(File oldFile, File copyFile)
	{
		try
		{
			if(oldFile != null && copyFile != null)
			{
				BufferedReader reader = new BufferedReader(new FileReader(oldFile));
				BufferedWriter writer = new BufferedWriter(new FileWriter(copyFile));

				String readedLine;

				while((readedLine = reader.readLine()) != null)
				{
					writer.append(readedLine);
					writer.newLine();
					writer.flush();
				}
				writer.close();
				reader.close();
			}
		}
		catch(Exception e)
		{
			log.catching(e);
		}
	}

	public static File getFileFromConfigFile(ConfigFile configFile)
	{
		return fileList.get(configFile);
	}

	public static ConfigFile getConfigFileFromName(String configurationFileName)
	{
		Iterator<ConfigFile> currentFile = fileList.keySet().iterator();

		while(currentFile.hasNext())
		{
			ConfigFile file = currentFile.next();
			if(file.getFileName().equals(configurationFileName))
				return file;
		}
		return null;
	}

	public BufferedWriter getWriter(File file) throws IOException
	{
		return new BufferedWriter(new FileWriter(file));
	}

	public BufferedReader getReader(File file) throws IOException
	{
		return new BufferedReader(new FileReader(file));
	}

	public void closeWriter(BufferedWriter writer) throws IOException
	{
		writer.flush();
		writer.close();
	}

	public void closeReader(BufferedReader reader) throws IOException
	{
		reader.close();
	}
}


text:
package de.aikiit.mailversendala;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * Main application that sends out mailings found in the configurable CSV file.
 * Remember to disable demo mode in order to send out mails.
 */
public class App {
    private static final Logger LOG =
            LogManager.getLogger(App.class);

    public static void main(String[] args) throws IOException {
        Mailversendala.sendOut(new MailConfig());
        LOG.info("Mailversendala is shutting down. Bye Bye :-)");
    }
}


text:
using namespace System.Reflection

function GetInferredType {
    <#
    .SYNOPSIS
        Attempts to determine the type of a variable within a script file.
    .DESCRIPTION
        This function first attempts to infer type from command completion context.  Failing that
        it will enumerate the scopes of any modules contained in the workspace as well as the global
        scope. If the variable is found in one of the scopes, the type of it's value will be returned.

        If the type cannot be inferred from command completion and the variable is defined in a function
        (or other child scope) this method will not work. The variable needs to be in a scope that
        exists at the time this function is ran. A workaround is to set a breakpoint right after the
        variable is defined.
    .INPUTS
        None
    .OUTPUTS
        System.Type

        Returns the inferred type if it was determined.  This function does not have output otherwise.
    .EXAMPLE
        PS C:\> GetInferredType -Ast $memberExpressionAst.Expression
        Determines the type of the variable used in a member expression.
    #>
    [CmdletBinding()]
    [OutputType([type])]
    param(
        # Specifies the current context of the editor.
        [Parameter(Position=0)]
        [ValidateNotNullOrEmpty()]
        [Microsoft.PowerShell.EditorServices.Extensions.EditorContext]
        $Context = $psEditor.GetEditorContext(),

        # Specifies the ast to analyze.
        [Parameter(Position=1, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.Language.Ast]
        $Ast
    )
    end {
        if ($Ast.InferredType -and $Ast.InferredType -ne ([object])) { return $Ast.InferredType }

        if ($Ast -is [System.Management.Automation.Language.TypeExpressionAst]) {
            return GetType -TypeName $Ast.TypeName
        }
        $PSCmdlet.WriteVerbose($Strings.InferringFromCompletion)
        $results = [System.Management.Automation.CommandCompletion]::CompleteInput(
            <# ast:            #> $Context.CurrentFile.Ast,
            <# tokens:         #> $Context.CurrentFile.Tokens,
            <# cursorPosition: #> $Ast.Extent.EndScriptPosition,
            <# options:        #> $null
        )
        $type = $results.CompletionMatches[0].ToolTip |
            Select-String '\[([\w\.]*)\]\$' |
            ForEach-Object { $PSItem.Matches.Groups[1].Value } |
            GetType

        if ($type -and $type.ToString() -match 'System.Collections' -or $type.IsArray) {
            $type = $null
        }
        if (-not $type -and $Ast -is [ExtendedMemberExpressionAst]) {
            $type = $Ast.InferredType
        }
        if (-not $type -and $Ast -is [System.Management.Automation.Language.MemberExpressionAst]) {

            $member = GetInferredMember $Ast
            $type = $member.ReturnType, $member.PropertyType, $member.FieldType | Where-Object { $_ }

        }
        # If it's a variable then check for it in scopes relevant to the current workspace.
        if (-not $type -and $Ast -is [System.Management.Automation.Language.VariableExpressionAst]) {
            $PSCmdlet.WriteVerbose($Strings.GettingImportedModules)

            $silent = @{
                ErrorAction   = 'Ignore'
                WarningAction = 'Ignore'
            }
            $workspaceModuleGuids = GetWorkspaceFile |
                Where-Object FullName -match '.psd1$' |
                Test-ModuleManifest @silent |
                Where-Object Guid -NotMatch '^[0-]*$' |
                ForEach-Object Guid

            $workspaceModules = Get-Module | Where-Object Guid -In $workspaceModuleGuids

            $internals = $workspaceModules | ForEach-Object {
                $PSItem.SessionState.GetType().
                    GetProperty('Internal', [BindingFlags]'Instance, NonPublic').
                    GetValue($PSItem.SessionState)
            }
            # If there are no modules in the workspace then grab the global scope. This isn't needed
            # otherwise because enumerating a module's scopes will hit global as well.
            if (-not $internals) {
                $PSCmdlet.WriteVerbose($Strings.CheckingDefaultScope)
                $internals = $ExecutionContext.SessionState.GetType().
                    GetProperty('Internal', [BindingFlags]'Instance, NonPublic').
                    GetValue($ExecutionContext.SessionState)
            }

            foreach ($internal in $internals) {
                $PSCmdlet.WriteVerbose($Strings.EnumeratingScopesForMember)
                $searcher = [ref].Assembly.GetType('System.Management.Automation.VariableScopeItemSearcher').
                    InvokeMember(
                        <# name:       #> '',
                        <# invokeAttr: #> [BindingFlags]'CreateInstance, Instance, Public',
                        <# binder:     #> $null,
                        <# target:     #> $null,
                        <# args:       #> @(
                            <# sessionState: #> $internal,
                            <# lookupPath:   #> $Ast.VariablePath,
                            <# origin:       #> [System.Management.Automation.CommandOrigin]::Runspace
                        )
                    )
                # Enumerate manually because enumerating normally sometimes causes an endless loop
                # with global variables.
                do { $match = $searcher.Current.Value }
                until ($match -or -not $searcher.MoveNext())

                if ($match.Count -gt 1) { $match = $match[0] }

                if ($match) {
                    $type = $match.GetType()
                    $PSCmdlet.WriteVerbose($Strings.VariableFound -f $type)
                    break
                }
            }
        }
        if (-not $type) {
            ThrowError -Exception ([InvalidOperationException]::new($Strings.CannotInferType -f $Ast)) `
                       -Id        CannotInferType `
                       -Category  InvalidOperation `
                       -Target    $Ast
        }
        $type
    }
}


text:
namespace chromeos {

namespace {

void WriteStringToFile(const base::FilePath path, const std::string& data) {
  ASSERT_TRUE(base::CreateDirectory(path.DirName()))
      << "Failed to create directory " << path.DirName().value();

  int size = data.size();
  ASSERT_TRUE(base::WriteFile(path, data.c_str(), size) == size)
      << "Failed to write " << path.value();
}

}  // namespace

// Provide basic sanity test of the FileFlusher. Note it only tests that
// flush is called for the expected files but not testing the underlying
// file system for actually persisting the data.
class FileFlusherTest : public testing::Test {
 public:
  FileFlusherTest() {}
  ~FileFlusherTest() override {}

  // testing::Test
  void SetUp() override {
    // Create test files under a temp dir.
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    const size_t kNumDirs = 2;
    const size_t kNumFiles = 3;
    for (size_t i = 1; i <= kNumDirs; ++i) {
      for (size_t j = 1; j <= kNumFiles; ++j) {
        const std::string path = base::StringPrintf("dir%zu/file%zu", i, j);
        const std::string content = base::StringPrintf("content %zu %zu", i, j);
        WriteStringToFile(temp_dir_.GetPath().AppendASCII(path), content);
      }
    }
  }

  void TearDown() override {
    content::BrowserThread::GetBlockingPool()->FlushForTesting();
    base::RunLoop().RunUntilIdle();
  }

  std::unique_ptr<FileFlusher> CreateFileFlusher() {
    std::unique_ptr<FileFlusher> flusher(new FileFlusher);
    flusher->set_on_flush_callback_for_test(
        base::Bind(&FileFlusherTest::OnFlush, base::Unretained(this)));
    return flusher;
  }

  base::FilePath GetTestFilePath(const std::string& path_string) const {
    const base::FilePath path = base::FilePath::FromUTF8Unsafe(path_string);
    if (path.IsAbsolute())
      return path;

    return temp_dir_.GetPath().Append(path);
  }

  void OnFlush(const base::FilePath& path) { ++flush_counts_[path]; }

  int GetFlushCount(const std::string& path_string) const {
    const base::FilePath path(GetTestFilePath(path_string));
    const auto& it = flush_counts_.find(path);
    return it == flush_counts_.end() ? 0 : it->second;
  }

 private:
  content::TestBrowserThreadBundle thread_bundle_;
  base::ScopedTempDir temp_dir_;
  std::map<base::FilePath, int> flush_counts_;

  DISALLOW_COPY_AND_ASSIGN(FileFlusherTest);
};

TEST_F(FileFlusherTest, Flush) {
  std::unique_ptr<FileFlusher> flusher(CreateFileFlusher());
  base::RunLoop run_loop;
  flusher->RequestFlush(GetTestFilePath("dir1"), std::vector<base::FilePath>(),
                        base::Closure());
  flusher->RequestFlush(GetTestFilePath("dir2"), std::vector<base::FilePath>(),
                        run_loop.QuitClosure());
  run_loop.Run();

  EXPECT_EQ(1, GetFlushCount("dir1/file1"));
  EXPECT_EQ(1, GetFlushCount("dir1/file2"));
  EXPECT_EQ(1, GetFlushCount("dir1/file3"));

  EXPECT_EQ(1, GetFlushCount("dir2/file1"));
  EXPECT_EQ(1, GetFlushCount("dir2/file2"));
  EXPECT_EQ(1, GetFlushCount("dir2/file3"));
}

TEST_F(FileFlusherTest, Exclude) {
  std::unique_ptr<FileFlusher> flusher(CreateFileFlusher());

  std::vector<base::FilePath> excludes;
  // Relative exclude
  excludes.push_back(base::FilePath::FromUTF8Unsafe("file1"));
  // Absolute exclude
  excludes.push_back(GetTestFilePath("dir1/file2"));
  // Invalid exclude will be ignored.
  excludes.push_back(base::FilePath::FromUTF8Unsafe("Bad file"));

  base::RunLoop run_loop;
  flusher->RequestFlush(GetTestFilePath("dir1"), excludes,
                        run_loop.QuitClosure());
  run_loop.Run();

  EXPECT_EQ(0, GetFlushCount("dir1/file1"));
  EXPECT_EQ(0, GetFlushCount("dir1/file2"));
  EXPECT_EQ(1, GetFlushCount("dir1/file3"));

  EXPECT_EQ(0, GetFlushCount("dir1/Bad file"));
}

TEST_F(FileFlusherTest, DuplicateRequests) {
  std::unique_ptr<FileFlusher> flusher(CreateFileFlusher());
  base::RunLoop run_loop;
  flusher->PauseForTest();
  flusher->RequestFlush(GetTestFilePath("dir1"), std::vector<base::FilePath>(),
                        base::Closure());
  flusher->RequestFlush(GetTestFilePath("dir1"), std::vector<base::FilePath>(),
                        run_loop.QuitClosure());
  flusher->ResumeForTest();
  run_loop.Run();

  EXPECT_EQ(1, GetFlushCount("dir1/file1"));
  EXPECT_EQ(1, GetFlushCount("dir1/file2"));
  EXPECT_EQ(1, GetFlushCount("dir1/file3"));
}

}  // namespace chromeos


text:
#include "goptionpane.h"
#include "platform.h"
using namespace std;

static Platform* pp = getPlatform();

void GOptionPane::showMessageDialog(string message, int /*type*/) {
    pp->goptionpane_showMessageDialog(message);
}

GOptionPaneResult GOptionPane::showConfirmDialog(string message) {
    int result = pp->goptionpane_showConfirmDialog(message);
    if (result == OK_OPTION) {
        return GOPTIONPANE_OK;
    } else if (result == CANCEL_OPTION) {
        return GOPTIONPANE_CANCEL;
    } else {
        return GOPTIONPANE_ERROR;
    }
}

string GOptionPane::showInputDialog(string message) {
    return pp->goptionpane_showInputDialog(message);
}

string GOptionPane::showOptionDialog(const Vector<string>& options, string initiallySelected) {
    return pp->goptionpane_showOptionDialog(options.toStlVector(), initiallySelected);
}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased] - unreleased

## v1.1.0 - 17/09/2015

### Feature
- Enable display of an existing image
- Enable replacing an existing image

## v1.0.1 - 04/03/2015

### Fixed
- Fix typo in package.json

## v1.0.0 - 03/03/2015

### Added
- Add photobooth directive


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.engine.test.api.task;

import static org.assertj.core.api.Assertions.assertThat;

import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.junit.jupiter.api.Test;

public class TaskBatchDeleteTest extends PluggableFlowableTestCase {

    /**
     * Validating fix for ACT-2070
     */
    @Test
    @Deployment
    public void testDeleteTaskWithChildren() throws Exception {

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testBatchDeleteOfTask");
        assertThat(processInstance).isNotNull();
        assertThat(processInstance.isEnded()).isFalse();

        // Get first task and finish. This should destroy the scope and trigger
        // some deletes, including:
        // org.flowable.task.service.Task 1, Identity link pointing to task 1, org.flowable.task.service.Task 2
        // The task deletes shouldn't be batched in this case, keeping the
        // related entity delete order
        org.flowable.task.api.Task firstTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey("taskOne").singleResult();
        assertThat(firstTask).isNotNull();

        taskService.complete(firstTask.getId());

        // Process should have ended fine
        processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(processInstance).isNull();

    }

    @Test
    @Deployment
    public void testDeleteCancelledMultiInstanceTasks() throws Exception {

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testBatchDeleteOfTask");
        assertThat(processInstance).isNotNull();
        assertThat(processInstance.isEnded()).isFalse();

        org.flowable.task.api.Task lastTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey("multiInstance").listPage(4, 1).get(0);

        taskService.addCandidateGroup(lastTask.getId(), "sales");

        org.flowable.task.api.Task firstTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey("multiInstance").listPage(0, 1).get(0);
        assertThat(firstTask).isNotNull();

        taskService.complete(firstTask.getId());

        // Process should have ended fine
        processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(processInstance).isNull();

        waitForHistoryJobExecutorToProcessAllJobs(7000, 100);

    }
}


text:
const HttpServer = require('./HttpServer')
const SoapServer = require('./SoapServer')
const SocketServer = require('./SocketServer')

module.exports = {
  HttpServer,
  SoapServer,
  SocketServer
}


text:
module ResourceInclusion
  module ClassMethods

    protected

    # Pass arguments to the serializer with the :include option, e.g.
    # object.to_xml(:include => your_args).
    def include_resource(*args)

      @included_resources = args.dup.freeze

      # TODO Is there a shortcut for appending a responder?
      unless self.responder.include?( ResourceInclusion::ResourceIncludeResponder )
        klass = Class.new( self.responder )
        klass.send(:include, ResourceInclusion::ResourceIncludeResponder)
        self.responder = klass
      end

    end

    alias include_resources include_resource

  end
end


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Comptatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<title>Backbone.js Books - Web app with Backbone.js + Google API</title>
	<meta name="description" content="Backbone Books is a little application using the Google Books API and coded with Backbone.js library. This application has been created by Sébastien Chopin.">
	<link rel="stylesheet" href="assets/css/main.css">
	<link href="https://fonts.googleapis.com/css?family=Sofia" rel="stylesheet" type="text/css">

Backbone.js Books

				Search : <input type="text" name="search" autocomplete="off" class="searchValue" value="Neuromarketing" />


text:
module Api
  class BaseController
    module Logger
      def log_request_initiated
        @requested_at = Time.now.utc
        return unless api_log_info?
        api_log_info(" ")
        log_request("API Request", :requested_at => @requested_at.to_s,
                                   :method       => request.request_method,
                                   :url          => request.original_url)
      end

      def log_api_auth
        return unless api_log_info?
        if @miq_token_hash
          auth_type = "system"
          log_request("System Auth", {:x_miq_token => request.headers[HttpHeaders::MIQ_TOKEN]}.merge(@miq_token_hash))
        else
          auth_type = @auth_token.blank? ? "basic" : "token"
        end
        log_request("Authentication", :type        => auth_type,
                                      :token       => @auth_token,
                                      :x_miq_group => request.headers[HttpHeaders::MIQ_GROUP],
                                      :user        => @auth_user)
        if User.current_user
          group = User.current_user.current_group
          log_request("Authorization", :user   => @auth_user,
                                       :group  => group.description,
                                       :role   => group.miq_user_role_name,
                                       :tenant => group.tenant.name)
        end
      end

      def log_api_request
        @parameter_filter ||= ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters)
        return unless api_log_info?
        log_request("Request", @req.to_hash)
        unfiltered_params = request.query_parameters
                                   .merge(params.permit(:action, :controller, :format).to_h)
                                   .merge("body" => @req.json_body)
        log_request("Parameters", @parameter_filter.filter(unfiltered_params))
        log_request_body
      end

      def log_api_response
        @completed_at = Time.now.utc
        return unless api_log_info?
        log_request("Response", :completed_at => @completed_at.to_s,
                                :size         => '%.3f KBytes' % (response.body.size / 1000.0),
                                :time_taken   => '%.3f Seconds' % (@completed_at - @requested_at),
                                :status       => response.status)
      end

      def api_log_debug?
        $api_log.debug?
      end

      def api_log_info?
        $api_log.info?
      end

      def api_get_method_name(call_stack, method)
        match = /`(?<mname>[^']*)'/.match(call_stack)
        (match ? match[:mname] : method).sub(/block .*in /, "")
      end

      def api_log_error(msg)
        method = api_get_method_name(caller.first, __method__)
        log_prefix = "MIQ(#{self.class.name}.#{method})"

        $api_log.error("#{log_prefix} #{ApiConfig.base.name} Error")
        msg.split("\n").each { |l| $api_log.error("#{log_prefix} #{l}") }
      end

      def api_log_debug(msg)
        if api_log_debug?
          method = api_get_method_name(caller.first, __method__)
          log_prefix = "MIQ(#{self.class.name}.#{method})"

          msg.split("\n").each { |l| $api_log.info("#{log_prefix} #{l}") }
        end
      end

      def api_log_info(msg)
        method = api_get_method_name(caller.first, __method__)
        log_prefix = "MIQ(#{self.class.name}.#{method})"

        msg.split("\n").each { |l| $api_log.info("#{log_prefix} #{l}") }
      end

      private

      def log_request_body
        log_request("Body", JSON.pretty_generate(@req.json_body)) if api_log_debug? && @req.json_body.present?
      end

      def log_request(header, data)
        api_log_info("#{('%s:' % header).ljust(15)} #{data}")
      end
    end
  end
end


text:
package jp.ac.nagoya_u.dsmoq.sdk.request.json

private[request] case class SetAccessLevelJson(id: String, ownerType: Int, accessLevel: Int) extends Jsonable


text:
import { Injectable, ViewMetadata, ComponentMetadata, reflector } from '@angular/core';
import { ReflectorReader } from '../core_private';
import { stringify, isBlank, isPresent } from '../src/facade/lang';
import { BaseException } from '../src/facade/exceptions';
import { Map } from '../src/facade/collection';
export class ViewResolver {
    constructor(_reflector) {
        /** @internal */
        this._cache = new Map();
        if (isPresent(_reflector)) {
            this._reflector = _reflector;
        }
        else {
            this._reflector = reflector;
        }
    }
    resolve(component) {
        var view = this._cache.get(component);
        if (isBlank(view)) {
            view = this._resolve(component);
            this._cache.set(component, view);
        }
        return view;
    }
    /** @internal */
    _resolve(component) {
        var compMeta;
        var viewMeta;
        this._reflector.annotations(component).forEach(m => {
            if (m instanceof ViewMetadata) {
                viewMeta = m;
            }
            if (m instanceof ComponentMetadata) {
                compMeta = m;
            }
        });
        if (isPresent(compMeta)) {
            if (isBlank(compMeta.template) && isBlank(compMeta.templateUrl) && isBlank(viewMeta)) {
                throw new BaseException(`Component '${stringify(component)}' must have either 'template' or 'templateUrl' set.`);
            }
            else if (isPresent(compMeta.template) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("template", component);
            }
            else if (isPresent(compMeta.templateUrl) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("templateUrl", component);
            }
            else if (isPresent(compMeta.directives) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("directives", component);
            }
            else if (isPresent(compMeta.pipes) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("pipes", component);
            }
            else if (isPresent(compMeta.encapsulation) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("encapsulation", component);
            }
            else if (isPresent(compMeta.styles) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("styles", component);
            }
            else if (isPresent(compMeta.styleUrls) && isPresent(viewMeta)) {
                this._throwMixingViewAndComponent("styleUrls", component);
            }
            else if (isPresent(viewMeta)) {
                return viewMeta;
            }
            else {
                return new ViewMetadata({
                    templateUrl: compMeta.templateUrl,
                    template: compMeta.template,
                    directives: compMeta.directives,
                    pipes: compMeta.pipes,
                    encapsulation: compMeta.encapsulation,
                    styles: compMeta.styles,
                    styleUrls: compMeta.styleUrls
                });
            }
        }
        else {
            if (isBlank(viewMeta)) {
                throw new BaseException(`Could not compile '${stringify(component)}' because it is not a component.`);
            }
            else {
                return viewMeta;
            }
        }
        return null;
    }
    /** @internal */
    _throwMixingViewAndComponent(propertyName, component) {
        throw new BaseException(`Component '${stringify(component)}' cannot have both '${propertyName}' and '@View' set at the same time"`);
    }
}
ViewResolver.decorators = [
    { type: Injectable },
];
ViewResolver.ctorParameters = [
    { type: ReflectorReader, },
];
//# sourceMappingURL=view_resolver.js.map


text:
SJ-Platform repository holds source code for Stream Juggler Platform Event Processing Engine.

Launch rest in docker:
docker run -d --name rest-ui -e MONGO_HOSTS=<mongo hosts> -e MONGO_USER=<mongo user> -e MONGO_PASSWORD=<mongo password> -e ZOOKEEPER_HOST=<zk host> -e ZOOKEEPER_PORT=<zk port> -p 8080:8080 bwsw/sj-rest


text:
<resources>
  <string name="app_name">gameloop</string>
  <string name="testing">Testing</string>
  <string name="test_complete">Game Loop Complete</string>
</resources>


text:
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;

public class ReuseGridMenu
{
    [MenuItem("NGUI/Create/Reuse Scroll View With Grid", false, 50)]
    static void AddReuseScrollViewAndGrid()
    {
        AddReuseScrollView();
        AddReuseGrid();
    }

    [MenuItem("NGUI/Create/Reuse Scroll View", false, 50)]
    static void AddReuseScrollView()
    {
        UIPanel panel = NGUISettings.AddPanel(NGUIEditorTools.SelectedRoot());
        if (panel == null) panel = NGUIEditorTools.SelectedRoot(true).GetComponent<UIPanel>();
        panel.clipping = UIDrawCall.Clipping.SoftClip;
        panel.name = "Reuse Scroll View";
        panel.gameObject.AddComponent<UIReuseScrollView>();
        Selection.activeGameObject = panel.gameObject;
    }

    [MenuItem("NGUI/Create/Reuse Grid", false, 50)]
    static void AddReuseGrid()
    {
        UIReuseGrid grid = NGUITools.AddChild<UIReuseGrid>(NGUIEditorTools.SelectedRoot());

        UIReuseScrollView scrollView = grid.transform.parent.GetComponent<UIReuseScrollView>();
        if (scrollView != null)
        {
            grid.m_ReuseScrollView = scrollView;
        }

        UIPanel panel = grid.transform.parent.GetComponent<UIPanel>();
        if (panel != null)
        {
            grid.transform.localPosition = new Vector3(panel.finalClipRegion.z * -0.5f + panel.finalClipRegion.x, panel.finalClipRegion.w * 0.5f + panel.finalClipRegion.y, 0.0f);
        }

        Selection.activeGameObject = grid.gameObject;
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </android.support.v4.view.ViewPager>

</LinearLayout>


text:
<form role="search" method="get" action="<?= esc_url(home_url('/')); ?>">
  <?php _e('Search for:', 'sage'); ?>

    <input type="search" value="<?= get_search_query(); ?>" name="s" placeholder="<?php _e('Search', 'sage'); ?> <?php bloginfo('name'); ?>" required>
      <button type="submit"><?php _e('Search', 'sage'); ?></button>

</form>


text:
param($installPath, $toolsPath, $package, $project)
Import-Module (Join-Path $toolsPath utilities.psm1)
Import-Module (Join-Path $toolsPath commands.psm1)
Import-Module (Join-Path $toolsPath visualstudio.psm1)


text:
using NUnit.Framework;
using SpaceInvaders.Core;
using SpaceInvaders.Entities;
using SpaceInvaders.Exceptions;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;

namespace SpaceInvadersTest.Tests
{
    [TestFixture]
    public class MapTest
    {
        [Test]
        public void TestAddEntity()
        {
            // Given
            var game = Match.GetInstance();
            game.StartNewGame();
            var map = new Map(11, 11);
            game.Map = map;
            var ship = new Ship(1) {X = 1, Y = 2};

            // When
            map.AddEntity(ship);

            // Then
            Assert.IsNotNull(map.GetEntity(ship.X, ship.Y), "Entity is null when it should be a space ship");
            Assert.IsNotNull(map.GetEntity(ship.X + 1, ship.Y), "Entity is null when it should be a space ship");
            Assert.IsNotNull(map.GetEntity(ship.X + 2, ship.Y), "Entity is null when it should be a space ship");

            Assert.IsNull(map.GetEntity(ship.X + 3, ship.Y), "Entity is not null when it should be");
        }

        [Test]
        public void TestRemoveEntity()
        {
            // Given
            var game = Match.GetInstance();
            game.StartNewGame();
            var map = new Map(11, 11);
            game.Map = map;
            var ship = new Ship(1) {X = 1, Y = 2};
            map.AddEntity(ship);

            // When
            map.RemoveEntity(ship);

            // Then
            Assert.IsNull(map.GetEntity(ship.X, ship.Y), "Entity should be null");
            Assert.IsNull(map.GetEntity(ship.X + 1, ship.Y), "Entity should be null");
            Assert.IsNull(map.GetEntity(ship.X + 2, ship.Y), "Entity should be null");
        }

        [Test]
        public void TestGetEntityOutOfBoundsReturnsNullTopLeft()
        {
            // Given
            var map = new Map(5, 5);

            // When
            var result = map.GetEntity(-1, -1);

            // Then
            Assert.IsNull(result, "Result should be null. No exception should be thrown.");
        }

        [Test]
        public void TestGetEntityOutOfBoundsReturnsNullBottomRight()
        {
            // Given
            var map = new Map(5, 5);

            // When
            var result = map.GetEntity(map.Width, map.Height);

            // Then
            Assert.IsNull(result, "Result should be null. No exception should be thrown.");
        }

        [Test]
        public void TestMoveOffMapDoesNotDeleteEntity()
        {
            // Given
            var map = new Map(5, 5);
            var wall = map.GetEntity(1, 0);

            // When
            MoveNotOnMapException exception = null;
            try
            {
                map.MoveEntity(wall, 1, -1);
            }
            catch (MoveNotOnMapException ex)
            {
                exception = ex;
            }

            wall = map.GetEntity(1, 0);

            // Then
            Assert.IsNotNull(exception, "MoveNotOnMapException was not thrown.");
            Assert.IsNotNull(wall, "Wall was deleted from the map by the attempt to move off it.");
        }
    }
}


text:
Helper functions to create data-driven map visualizations.

Take the advantage of [CARTOColors](https://carto.com/carto-colors/), custom color schemes built on top of well-known standards for color use on maps, with next generation enhancements for the web and CARTO basemaps.

## colorBins

Helper function for quickly creating a color bins style.

Data values of each attribute are rounded down to the nearest value in the domain and are then styled with the corresponding color.

```javascript
new CartoSQLLayer({
  data: 'SELECT the_geom_webmercator, gn_pop FROM populated_places',
  getFillColor:  colorBins({
    attr: 'gn_pop',
    domain: [1e5, 2e5, 3e5],
    colors: 'Teal'
  })
});
```

### Arguments

#### `attr` (String)

Attribute or column to symbolize by.

#### `domain` (Array)

Assign manual class break values.

#### `colors` (String | Array, optional)

Color assigned to each domain value.

- String: A valid named [CARTOColors](https://carto.com/carto-colors/) palette.
- Array: Array of colors in RGBA `[ [r, g, b, [a]] ]`.

Default: `PurpOr`

#### `nullColor` (Array, optional)

Color for null values.

Default: `[204, 204, 204]`

## colorCategories

Helper function for quickly creating a color category style.

Data values of each attribute listed in the domain are mapped one to one with corresponding colors in the range.

```javascript
new CartoSQLLayer({
  data: 'SELECT the_geom_webmercator, type FROM ne_10m_airports',
  getFillColor: colorCategories({
    attr: 'type',
    domain: ['mid', 'major', 'military mid', 'mid and military', 'major and military'],
    colors: 'Bold'
  })
});
```

### Arguments

#### `attr` (String)

Attribute or column to symbolize by.

#### `domain` (Array)

Category list. Must be a valid list of categories.

#### `colors` (String | Array, optional)

Color assigned to each domain value.

- String: A valid named [CARTOColors](https://carto.com/carto-colors/) palette.
- Array: Array of colors in RGBA `[ [r, g, b, [a]] ]`.

Default: `PurpOr`

#### `nullColor` (Array, optional)

Color for null values.

Default: `[204, 204, 204]`

#### `othersColor` (Array, optional)

Fallback color for a category not correctly assigned.

Default: `[119, 119, 119]`

## Color Continuous

Helper function for quickly creating a color continuous style.

Data values of each field are interpolated linearly across values in the domain and are then styled with a blend of the corresponding color in the range.

```javascript
new CartoSQLLayer({
  data: 'SELECT the_geom_webmercator, gn_pop FROM populated_places',
  getFillColor: colorContinuous({
    attr: 'gn_pop',
    domain: [0, 1e5],
    colors: 'BluYl'
  })
});
```

### Arguments

#### `attr` (String)

Attribute or column to symbolize by.

#### `domain` (Array)

Attribute domain to define the data range.

#### `colors` (String | Array, optional)

Color assigned to each domain value.

- String: A valid named [CARTOColors](https://carto.com/carto-colors/) palette.
- Array: Array of colors in RGBA `[ [r, g, b, [a]] ]`.

Default: `PurpOr`

#### `nullColor` (Array, optional)

Color for null values.

Default: `[204, 204, 204]`


text:
<?php
$data = cx::data('item.data');
list($img_width, $img_height) = getimagesize($data['image_url']);
?>
<!doctype html>

    <meta charset="utf-8">
    <title><?=cx::title()?></title>
    <link rel="canonical" href="<?=cx::canonical()?>">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">

        <a href="<?=URL?>"><?=cx::option('app.name')?>

<?=$data['title']?>

        <?=amp::content_filter($data['content'])?>

        <?=cx::option('app.name')?>

<amp-analytics type="googleanalytics" id="analytics1">

</amp-analytics>


text:
* [ObjectType](ts.objecttype.md)

## Index

### Properties
* [baseArrayType](ts.tupletype.md#basearraytype)
* [elementTypes](ts.tupletype.md#elementtypes)
* [flags](ts.tupletype.md#flags)
* [id](ts.tupletype.md#id)
* [symbol](ts.tupletype.md#symbol)

## Properties

### baseArrayType: [TypeReference](ts.typereference.md)

* Defined in [lib/typescript/tsc.d.ts:1364](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1364)

### elementTypes: [Type](ts.type.md)[]

* Defined in [lib/typescript/tsc.d.ts:1363](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1363)

### flags: [TypeFlags](../enums/ts.typeflags.md)

* Inherited from [Type](ts.type.md).[flags](ts.type.md#flags)
* Defined in [lib/typescript/tsc.d.ts:1329](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1329)

### id: number

* Inherited from [Type](ts.type.md).[id](ts.type.md#id)
* Defined in [lib/typescript/tsc.d.ts:1330](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1330)

### Optional symbol: [Symbol](ts.symbol.md)

* Inherited from [Type](ts.type.md).[symbol](ts.type.md#symbol)
* Defined in [lib/typescript/tsc.d.ts:1331](https://github.com/kimamula/typedoc/blob/HEAD/src/lib/typescript/tsc.d.ts#L1331)

Generated using [TypeDoc](http://typedoc.io)