text:
package com.steven.sports.home.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.steven.sports.BaseFragment;
import com.steven.sports.MyApplication;
import com.steven.sports.R;
import com.steven.sports.home.model.LoadMoreFooterAdapter;
import com.steven.sports.home.model.Sport;
import com.steven.sports.home.model.SportAdapter;
import com.steven.sports.home.presenter.DiscoverContract;
import com.steven.sports.home.presenter.DissoverPresenter;
import com.steven.sports.home.presenter.RecyclerViewItemClickListener;
import com.steven.sports.util.HttpConstant;
import com.steven.sports.util.Zlog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DiscoverFragment extends BaseFragment implements DiscoverContract.View,
        AdapterView.OnItemSelectedListener, RecyclerViewItemClickListener {

    @BindView(R.id.discover_spn_type)
    Spinner mSpnTypes;
    @BindView(R.id.discover_spn_distance)
    Spinner mSpnDistances;
    @BindView(R.id.discover_spn_time)
    Spinner mSpnTimes;
    @BindView(R.id.discover_recycler_view)
    LRecyclerView mRecyclerView;
    @BindView(R.id.discover_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    public static final String BROADCAST_SPORTS_DATA_CHANGE = "com.steven.sports.discover.SPORTS_DATA_CHANGE";
    private static final int DISTANCE_10K = 10 * 1000;
    private static final int DISTANCE_5K = 5 * 1000;
    private static final int LOCATION_REFRESH_SPAN = 500;

    private HomeActivity mActivity;
    private DiscoverContract.Presenter mPresenter;
    private List<Sport> mSportList = new CopyOnWriteArrayList<>();
    private LoadMoreFooterAdapter mSportAdapter;

    private SportsDataChangeReceiver mSportsReceiver;
    private LocalBroadcastManager mLocalBroadcastManager;

    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private BDLocation mLocation;

    // three spinner and change spinner adapter will auto call onItemSelected, set flag to check if auto call
    private int mSpinnerCheck = 4;
    private int mPage = 0;

    public static DiscoverFragment newInstance() {
        return new DiscoverFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected int bindLayout() {
        return R.layout.fragment_discover;
    }

    @Override
    public void init(View view) {
        ButterKnife.bind(this, view);

        mActivity = (HomeActivity) getActivity();
        mPresenter = new DissoverPresenter(this);

        initRecyclerView();
        initSpinner();
        initBroadcast();
        initLocation();
        refreshSportItems("init", true);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshSportItems("onSwipeRefresh", true);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void initRecyclerView() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        SportAdapter adapter = new SportAdapter(mSportList, this);
        mSportAdapter = new LoadMoreFooterAdapter(adapter);
        mRecyclerView.setAdapter(mSportAdapter);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setOnLoadMoreListener(new LRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                mPage++;
                refreshSportItems("RecyclerView onLoadMore", false);
            }
        });
        mRecyclerView.setOnNetworkErrorListener(new LRecyclerView.OnNetworkErrorListener() {
            @Override
            public void onNetworkError() {
                refreshSportItems("RecyclerView onNetworkError", true);
            }
        });
    }

    private void initSpinner() {
        List<String> list = new ArrayList<>();
        String[] types = getResources().getStringArray(R.array.sport_types);
        list.addAll(Arrays.asList(types));
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(this.getContext(), android.R.layout.simple_dropdown_item_1line);
        typeAdapter.add("全部");
        typeAdapter.addAll(list);
        mSpnTypes.setAdapter(typeAdapter);

        if (mLocation != null) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(DiscoverFragment.this.getContext(),
                    android.R.layout.simple_dropdown_item_1line);
            String cityName = mLocation.getCity();
            adapter.add("全" + cityName.substring(0, cityName.length() - 1));
            adapter.add(mLocation.getDistrict());
            adapter.add("10km");
            adapter.add("5km");
            mSpnDistances.setAdapter(adapter);
        }

        mSpnTypes.setOnItemSelectedListener(this);
        mSpnTimes.setOnItemSelectedListener(this);
        mSpnDistances.setOnItemSelectedListener(this);
    }

    private void initBroadcast() {
        mSportsReceiver = new SportsDataChangeReceiver();
        IntentFilter sportFilter = new IntentFilter();
        sportFilter.addAction(BROADCAST_SPORTS_DATA_CHANGE);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(MyApplication.getContext());
        mLocalBroadcastManager.registerReceiver(mSportsReceiver, sportFilter);
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setScanSpan(LOCATION_REFRESH_SPAN);
        mLocationClient = new LocationClient(mActivity.getApplicationContext(), option);
        mLocationListener = new MyLocationListener();
        if (mActivity.haveAllPermission() && mLocation == null) {
            mLocationClient.registerLocationListener(mLocationListener);
            mLocationClient.start();
        }
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null && location.getLocType() != BDLocation.TypeServerError) {
                mLocation = location;

                // setAdapter will auto call onItemSelected
                mSpinnerCheck += 2;
                initSpinner();
                mPage = 0;
                mSportList.clear();
                refreshSportItems("onReceiveLocation", true);

                mLocationClient.unRegisterLocationListener(mLocationListener);
                mLocationClient.stop();
            }
        }
    }

    private void refreshSportItems(String from, boolean needReload) {
        if (mLocation == null || mLocation.getCity() == null || mLocation.getDistrict() == null) {
            mSwipeRefreshLayout.setRefreshing(false);
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient.stop();
            mLocationClient.registerLocationListener(mLocationListener);
            mLocationClient.start();
            return;
        }
        mSwipeRefreshLayout.setRefreshing(true);

        String type = mSpnTypes.getSelectedItem().toString();
        String currentTimeStr = new SimpleDateFormat("yyyyMMddHHmm", Locale.CHINA).format(new Date());
        long time = Long.valueOf(currentTimeStr);
        // should be the same as -> arrays.xml discover_times
        int item = mSpnTimes.getSelectedItemPosition();
        if (item == 0) { // 一个月内
            time += 1000000;
        } else if (item == 1) { // 一周内
            time += 70000;
        } else if (item == 2) { // 三天内
            time += 30000;
        } else if (item == 3) { // 24 小时内
            time += 10000;
        }

        String district = Sport.FLAG_NO_DISTRICT;
        int distance = Sport.FLAG_NO_DISTANCE;
        item = mSpnDistances.getSelectedItemPosition();
        if (item == 1) {
            district = mLocation.getDistrict();
        } else if (item == 2) {
            distance = DISTANCE_10K;
        } else if (item == 3) {
            distance = DISTANCE_5K;
        }

        if (needReload) {
            mPage = 0;
        }
        Zlog.d(TAG, "refreshSportItems from " + from + ", type: " + type + ", time: " + time + ", city: "
                + mLocation.getCity() + ", page: " + mPage + ", listSize: " + mSportList.size());
        mPresenter.getNearbySports(type, String.valueOf(time), mLocation.getCity(), district,
                distance, mLocation.getLatitude(), mLocation.getLongitude(), mPage, needReload);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (mSpinnerCheck-- > 0) {
            return;
        }
        refreshSportItems("onSpinnerItemSelected", true);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onRecyclerViewItemClicked(View view, int position) {
        Sport sport = mSportList.get(position);
        SportDetailActivity.actionStart(getContext(), sport, mActivity.getUserPhone());
    }

    @Override
    public void onRecyclerViewItemLongClicked(View view, int position) {

    }

    @Override
    public void showMessage(int stringId) {
        Toast.makeText(getContext(), getText(stringId), Toast.LENGTH_SHORT).show();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void getSportsSucceed(String allSportJsonStr, boolean needRefresh) {
        mSwipeRefreshLayout.setRefreshing(false);
        if (needRefresh) {
            mSportList.clear();
        }
        if (allSportJsonStr == null || allSportJsonStr.equals("")) {
            mSportAdapter.notifyDataSetChanged();
            mRecyclerView.footerSetNoMore();
            if (!needRefresh) {
                mPage--;
            }
            return;
        }
        String[] sportJsons = allSportJsonStr.split(HttpConstant.KEY_SPLIT_JSON);
        for (String jsonStr : sportJsons) {
            Sport sport = JSON.parseObject(jsonStr, Sport.class);
            mSportList.add(sport);
        }
        mSportAdapter.notifyDataSetChanged();
        mRecyclerView.footerSetPrepare();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient.isStarted()) {
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient.stop();
        }
        mLocalBroadcastManager.unregisterReceiver(mSportsReceiver);
    }

    class SportsDataChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshSportItems("onReceive", true);
        }

    }

}


text:
package com.netflix.governator.lifecycle.warmup;

import com.google.common.collect.Sets;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Set;

public class TestDAGManager
{
    @Test
    public void     testSingleRoot()
    {
        DAGManager      manager = new DAGManager();
        manager.addDependency("A", "B");
        manager.addDependency("A", "C");

        DependencyNode  root = manager.generateTree();
        Assert.assertEquals(root.getChildren().size(), 1);

        DependencyNode  aNode = root.getChildren().get(0);
        Assert.assertEquals(aNode.getKey(), "A");
        Assert.assertEquals(aNode.getChildren().size(), 2);

        Set<Object>     set = Sets.newHashSet();
        set.add(aNode.getChildren().get(0).getKey());
        set.add(aNode.getChildren().get(1).getKey());
        Assert.assertEquals(set, Sets.newHashSet("B", "C"));
    }

    @Test
    public void     testSingleRootDepsBothDirections()
    {
        DAGManager      manager = new DAGManager();
        manager.addDependency("A", "B");
        manager.addDependency("A", "C");
        manager.addDependency("B", "C");

        DependencyNode  root = manager.generateTree();
        Assert.assertEquals(root.getChildren().size(), 1);

        DependencyNode  aNode = root.getChildren().get(0);
        Assert.assertEquals(aNode.getKey(), "A");
        Assert.assertEquals(aNode.getChildren().size(), 2);
        Assert.assertEquals(aNode.getChildren().get(0).getKey(), "B");
        Assert.assertEquals(aNode.getChildren().get(1).getKey(), "C");
    }

    @Test
    public void     testMultiRoots()
    {
        DAGManager      manager = new DAGManager();
        manager.addDependency("A", "C");
        manager.addDependency("B", "C");

        DependencyNode  root = manager.generateTree();
        Assert.assertEquals(root.getChildren().size(), 2);

        Set<Object>     set = Sets.newHashSet();
        set.add(root.getChildren().get(0).getKey());
        set.add(root.getChildren().get(1).getKey());
        Assert.assertEquals(set, Sets.newHashSet("A", "B"));

        Assert.assertEquals(root.getChildren().get(0).getChildren().size(), 1);
        Assert.assertEquals(root.getChildren().get(0).getChildren().get(0).getKey(), "C");

        Assert.assertEquals(root.getChildren().get(1).getChildren().size(), 1);
        Assert.assertEquals(root.getChildren().get(1).getChildren().get(0).getKey(), "C");
    }

    @Test
    public void     testMultiRootsDepsBothDirections()
    {
        DAGManager      manager = new DAGManager();
        manager.addDependency("A", "C");
        manager.addDependency("C", "D");
        manager.addDependency("B", "D");

        DependencyNode  root = manager.generateTree();
        Assert.assertEquals(root.getChildren().size(), 2);

        Set<Object>     set = Sets.newHashSet();
        set.add(root.getChildren().get(0).getKey());
        set.add(root.getChildren().get(1).getKey());
        Assert.assertEquals(set, Sets.newHashSet("A", "B"));

        Assert.assertEquals(root.getChildren().get(0).getChildren().size(), 1);
        Assert.assertEquals(root.getChildren().get(1).getChildren().size(), 1);

        Object child0ChildKey = root.getChildren().get(0).getChildren().get(0).getKey();
        Object child1ChildKey = root.getChildren().get(1).getChildren().get(0).getKey();

        Assert.assertTrue(child0ChildKey.equals("C") || child0ChildKey.equals("D"), child0ChildKey.toString());
        Assert.assertTrue(child1ChildKey.equals("C") || child1ChildKey.equals("D"), child1ChildKey.toString());

        int         nextIndex = child0ChildKey.equals("C") ? 0 : 1;
        Assert.assertEquals(root.getChildren().get(nextIndex).getChildren().get(0).getChildren().size(), 1);
        Assert.assertEquals(root.getChildren().get(nextIndex).getChildren().get(0).getChildren().get(0).getKey(), "D");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclairjs.nashorn;

import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.core.IsInstanceOf.*;

import javax.script.Invocable;
import javax.script.ScriptEngine;

public class SparkContextTest {

	@Test
    public void addInt() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("addInt");

         assertEquals("failure - values are not equal", 10, ret);

    };

    @Test
    public void addFloat() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("addFloat");

         assertEquals("failure - values are not equal", 11.0, ret);

    };

    @Test
    public void addFloatAccumulable() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("addFloatAccumulable");

         assertEquals("failure - values are not equal", 11.0, ret);

    };

    @Test
    public void intAccumulatorParam() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("intAccumulatorParam");

         assertEquals("failure - values are not equal", 10, ret);

    };

    @Test
    public void floatAccumulatorParam() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("floatAccumulatorParam");

         assertEquals("failure - values are not equal", 11.0, ret);

    };

    @Test
    public void floatAccumulator() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("floatAccumulator");

         assertEquals("failure - values are not equal", 11.0, ret);

    };

    @Test
    public void scFloatAccumulator() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("scFloatAccumulator");

         assertEquals("failure - values are not equal", 11.0, ret);

    };

    @Test
    public void scIntAccumulator() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
       // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("scIntAccumulator");

         assertEquals("failure - values are not equal", 10, ret);

    };

    @Test
    public void broadcast() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
        // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("broadcast");

        assertEquals("failure - values are not equal", "[1,2]", ret);

    };

    @Test
    public void objectFile() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
        // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("objectFile");

        assertEquals("failure - values are not equal", "[{\"user\":0,\"product\":260,\"rating\":9}]", ret);

    };

    @Test
    public void textFile() throws Exception {
        ScriptEngine engine = TestUtils.getEngine();
        // String file = TestUtils.resourceToFile("/dream.txt");

        TestUtils.evalJSResource(engine, "/sparkcontexttests.js");
        Object ret = ((Invocable)engine).invokeFunction("textFile");

        assertEquals("failure - values are not equal", "[\"Rating(0,260,9.0)\"]", ret);

    };
}


text:
package com.example.haotianzhu.noname;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;

/**
 * This activity class is used to update data for an existing habit including its title, start_date, routine etc.
 * @author   Haotian Zhu
 * @author   Yuhang Xiong
 * @author   Yuntian Zhang
 * @author   Wenhan Yang*/
public class EditHabitActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
    private static habit editHabit;
    private String userID;
    private String title;
    private String reason;
    private ArrayList<Integer> routine;
    private EditText titleText;
    private EditText reasonText;
    private TextView startDateText;
    private int day,month,year ;
    private Button routineButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_habit);

        editHabit = (habit) getIntent().getBundleExtra("send").getSerializable("EditHabit");
        Button doneButton = (Button) findViewById(R.id.done);
        Button cancelButton = (Button) findViewById(R.id.cancel);
        final Button deleteButton = (Button) findViewById(R.id.delete);
        routineButton = (Button) findViewById(R.id.routine);
        Button startDateButton = (Button) findViewById(R.id.startDate);
        titleText = (EditText) findViewById(R.id.habitTitle);
        reasonText = (EditText) findViewById(R.id.habitReason);
        startDateText = (TextView) findViewById(R.id.startDateText);

        userID = editHabit.getUserID();
        title = editHabit.getTitle();
        reason =editHabit.getReason();
        routine = editHabit.getRouting();
        year = editHabit.getYear();
        month = editHabit.getMonth();
        day = editHabit.getDay();

        titleText.setHint("Title: "+title);
        reasonText.setHint("Reason: "+reason);
        startDateText.setText(dateToString(year,month,day));
        routineButton.setText(ConvertRoutine(routine));

        startDateButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                DatePickerDialog datePickerDialog = new DatePickerDialog(EditHabitActivity.this,EditHabitActivity.this,year,month-1,day);
                datePickerDialog.show();

            }
        });

        routineButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Intent intent = new Intent(EditHabitActivity.this,PopUpWindowActivity.class);
                intent.putIntegerArrayListExtra("routine", routine);
                startActivityForResult(intent,5);
            }
        });

        //set result as canceled and finish this activity, go back to last controller
        cancelButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });

        deleteButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Elasticsearch.DeleteHabitsTask deleteHabitsTask = new Elasticsearch.DeleteHabitsTask();
                deleteHabitsTask.execute(editHabit);
                Elasticsearch.GetEventsTask getEventsTask = new Elasticsearch.GetEventsTask();
                String q = "{\"query\" : {\"match\" : { \"habitTypeID\" : \""+editHabit.getId().toLowerCase().replaceAll("-","")+"\" }}}";
                getEventsTask.execute(q);

                try {
                    ArrayList<habitEvent> events = getEventsTask.get();
                    Elasticsearch.DeleteEventsTask deleteEventsTask = new Elasticsearch.DeleteEventsTask();
                    deleteEventsTask.execute(events);

                    setResult(-100);
                }catch (Exception e){
                    Log.i("Error",e.toString());

                }
                finish();
            }
        });

        // press done => check result ok
        // if ok setResult and bundles results and return back to last controller
        doneButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                String newtitle = titleText.getText().toString().toLowerCase();
                String newreason = reasonText.getText().toString().toLowerCase();

                if(! newtitle.equals("")){
                    title = newtitle.toLowerCase();
                }
                if(! newreason.equals("")){
                    reason = newreason.toLowerCase();
                }
                editHabit.editReason(reason);
                editHabit.editTitle(title);
                editHabit.editRouting(routine);
                editHabit.editYear(year);
                editHabit.editMonth(month);
                editHabit.editDay(day);
                Elasticsearch.UpdateHabitTask updateHabitTask = new Elasticsearch.UpdateHabitTask();
                updateHabitTask.execute(editHabit);

                Intent resultIntent = new Intent();
                Bundle result = new Bundle();
                result.putSerializable("EditHabit",editHabit);
                resultIntent.putExtra("result",result);
                setResult(RESULT_OK,resultIntent);
                finish();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == 5) {
            if (resultCode == RESULT_OK) {
                routine =  data.getIntegerArrayListExtra("routine");
                routineButton.setText(ConvertRoutine(routine));
            }
        }
    }

    public String dateToString(int y,int m,int d){
        return  " year: "+y+" month: "+(m)+" day: " +d ;
    }

    protected String ConvertRoutine(ArrayList<Integer> routine) {
        if (routine.isEmpty()) {
            return "Repeat: never";
        } else {
            Integer i=0;
            String returnString = "Repeat: ";
            if (routine.contains(1)) {
                returnString += "Monday ";
                i+=1;
            }
            if (routine.contains(2)) {
                returnString += "Tuesday ";
                i+=1;
            }
            if (routine.contains(3)) {
                returnString += "Wednesday ";
                i+=1;
            }
            if (routine.contains(4)) {
                returnString += "Thursday ";
                i+=1;
            }
            if (routine.contains(5)) {
                returnString += "Friday ";
                i+=1;
            }
            if (routine.contains(6)) {
                returnString += "Saturday ";
                i+=1;
            }
            if (routine.contains(7)) {
                returnString += "Sunday ";
                i+=1;
            }
            if (i==7){
                return "Repeat everyday ";
            }
            else{
                return returnString;
            }
        }
    }
    @Override
    public void onDateSet(DatePicker datePicker, int i, int i1, int i2){
        year = i;
        month = i1+1;
        day = i2;
        startDateText.setText(dateToString(year,month,day));
    }

}


text:
package com.smartdevicelink.proxy.rpc;

import com.smartdevicelink.proxy.RPCStruct;

import java.util.Hashtable;

/**
 * @since SmartDeviceLink 3.0
 */

public class Headers extends RPCStruct {
    public static final String KEY_CONTENT_TYPE = "ContentType";
    public static final String KEY_CONNECT_TIMEOUT = "ConnectTimeout";
    public static final String KEY_DO_OUTPUT = "DoOutput";
    public static final String KEY_DO_INPUT = "DoInput";
    public static final String KEY_USE_CACHES = "UseCaches";
    public static final String KEY_REQUEST_METHOD = "RequestMethod";
    public static final String KEY_READ_TIMEOUT = "ReadTimeout";
    public static final String KEY_INSTANCE_FOLLOW_REDIRECTS = "InstanceFollowRedirects";
    public static final String KEY_CHARSET = "charset";
    public static final String KEY_CONTENT_LENGTH = "Content-Length";

    public Headers() {
    }

    /**
     * <p>
     * Constructs a new Headers object indicated by the Hashtable
     * parameter
     * </p>
     *
     * @param hash The Hashtable to use
     */

    public Headers(Hashtable<String, Object> hash) {
        super(hash);
    }

    public Headers setContentType(String contentType) {
        setValue(KEY_CONTENT_TYPE, contentType);
        return this;
    }

    public String getContentType() {
        return getString(KEY_CONTENT_TYPE);
    }

    public Headers setConnectTimeout(Integer connectionTimeout) {
        setValue(KEY_CONNECT_TIMEOUT, connectionTimeout);
        return this;
    }

    public Integer getConnectTimeout() {
        return getInteger(KEY_CONNECT_TIMEOUT);
    }

    public Headers setDoOutput(Boolean doOutput) {
        setValue(KEY_DO_OUTPUT, doOutput);
        return this;
    }

    public Boolean getDoOutput() {
        return getBoolean(KEY_DO_OUTPUT);
    }

    public Headers setDoInput(Boolean doInput) {
        setValue(KEY_DO_INPUT, doInput);
        return this;
    }

    public Boolean getDoInput() {
        return getBoolean(KEY_DO_INPUT);
    }

    public Headers setUseCaches(Boolean usesCaches) {
        setValue(KEY_USE_CACHES, usesCaches);
        return this;
    }

    public Boolean getUseCaches() {
        return getBoolean(KEY_USE_CACHES);
    }

    public Headers setRequestMethod(String requestMethod) {
        setValue(KEY_REQUEST_METHOD, requestMethod);
        return this;
    }

    public String getRequestMethod() {
        return getString(KEY_REQUEST_METHOD);
    }

    public Headers setReadTimeout(Integer readTimeout) {
        setValue(KEY_READ_TIMEOUT, readTimeout);
        return this;
    }

    public Integer getReadTimeout() {
        return getInteger(KEY_READ_TIMEOUT);
    }

    public Headers setInstanceFollowRedirects(Boolean instanceFollowRedirects) {
        setValue(KEY_INSTANCE_FOLLOW_REDIRECTS, instanceFollowRedirects);
        return this;
    }

    public Boolean getInstanceFollowRedirects() {
        return getBoolean(KEY_INSTANCE_FOLLOW_REDIRECTS);
    }

    public Headers setCharset(String charset) {
        setValue(KEY_CHARSET, charset);
        return this;
    }

    public String getCharset() {
        return getString(KEY_CHARSET);
    }

    public Headers setContentLength(Integer contentLength) {
        setValue(KEY_CONTENT_LENGTH, contentLength);
        return this;
    }

    public Integer getContentLength() {
        return getInteger(KEY_CONTENT_LENGTH);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.AI.TextAnalytics;
using Azure.Core;

namespace Azure.AI.TextAnalytics.Models
{
    /// <summary> The CustomLabelClassificationResult. </summary>
    internal partial class CustomLabelClassificationResult : CustomResult
    {
        /// <summary> Initializes a new instance of CustomLabelClassificationResult. </summary>
        /// <param name="errors"> Errors by document id. </param>
        /// <param name="projectName"> This field indicates the project name for the model. </param>
        /// <param name="deploymentName"> This field indicates the deployment name for the model. </param>
        /// <param name="documents"> Response by document. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="errors"/>, <paramref name="projectName"/>, <paramref name="deploymentName"/> or <paramref name="documents"/> is null. </exception>
        public CustomLabelClassificationResult(IEnumerable<DocumentError> errors, string projectName, string deploymentName, IEnumerable<CustomLabelClassificationResultDocumentsItem> documents) : base(errors, projectName, deploymentName)
        {
            Argument.AssertNotNull(errors, nameof(errors));
            Argument.AssertNotNull(projectName, nameof(projectName));
            Argument.AssertNotNull(deploymentName, nameof(deploymentName));
            Argument.AssertNotNull(documents, nameof(documents));

            Documents = documents.ToList();
        }

        /// <summary> Initializes a new instance of CustomLabelClassificationResult. </summary>
        /// <param name="errors"> Errors by document id. </param>
        /// <param name="statistics"> if showStats=true was specified in the request this field will contain information about the request payload. </param>
        /// <param name="projectName"> This field indicates the project name for the model. </param>
        /// <param name="deploymentName"> This field indicates the deployment name for the model. </param>
        /// <param name="documents"> Response by document. </param>
        internal CustomLabelClassificationResult(IList<DocumentError> errors, TextDocumentBatchStatistics statistics, string projectName, string deploymentName, IList<CustomLabelClassificationResultDocumentsItem> documents) : base(errors, statistics, projectName, deploymentName)
        {
            Documents = documents;
        }

        /// <summary> Response by document. </summary>
        public IList<CustomLabelClassificationResultDocumentsItem> Documents { get; }
    }
}


text: module.exports = () => "Successfully called dummy-plugin-2";


text:
package org.hoteia.qalingo.core.service;

import java.util.List;

import org.hoteia.qalingo.core.domain.AbstractRuleReferential;

public interface RuleReferentialService {

	AbstractRuleReferential getRuleReferentialByRuleType(String ruleType);

	AbstractRuleReferential getRuleReferentialByCode(String code);

	List<AbstractRuleReferential> findRuleReferentials();

	void saveRuleReferential(AbstractRuleReferential ruleReferential);

	void deleteRuleReferential(AbstractRuleReferential ruleReferential);

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.UI.Notifications;
using Windows.ApplicationModel.VoiceCommands;

namespace ArcherSysOS.DoctorCortana
{
    public sealed class DoctorCortana : IBackgroundTask

    {
        BackgroundTaskDeferral serviceDeferral;
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if(triggerDetails != null && triggerDetails.Name == "DoctorCortanaEndpoint")
            {
                try
                {
                    VoiceCommandServiceConnection vsvc = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    vsvc.VoiceCommandCompleted += Vsvc_VoiceCommandCompleted;
                    VoiceCommand vcmd = await vsvc.GetVoiceCommandAsync();
                    switch (vcmd.CommandName)
                    {
                        case "codebaseQuery":
                            VoiceCommandUserMessage successmsg = new VoiceCommandUserMessage();
                            successmsg.DisplayMessage = "Malaika says it's made of mostly PHP, CSharp, and JavaScript code.";
                            successmsg.SpokenMessage = "My friend Malaika says that Mr.Henson made ArcherSysOS out of PHP,JavaScript and C Sharp.";
                            VoiceCommandResponse vcr = VoiceCommandResponse.CreateResponse(successmsg);
                            await vsvc.ReportProgressAsync(vcr);
                            break;

                    }

                }catch(Exception e)
                {
                    VoiceCommandServiceConnection vsvc = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    vsvc.VoiceCommandCompleted += Vsvc_VoiceCommandCompleted;
                    VoiceCommandUserMessage err = new VoiceCommandUserMessage();
                    err.DisplayMessage = e.Message;
                    err.SpokenMessage = " I'm Sorry, but I can't talk to the ArcherSysOS team right now. try again later";
                    var  errresp = VoiceCommandResponse.CreateResponse(err);
                    await vsvc.RequestAppLaunchAsync(errresp);

                }
            }
        }

        private void Vsvc_VoiceCommandCompleted(VoiceCommandServiceConnection sender, VoiceCommandCompletedEventArgs args)
        {
            Debug.Write("Command Completed.");
            if(this.serviceDeferral != null)
            {
                this.serviceDeferral.Complete();
            }
        }

        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            Debug.Write("Task was canceled.");
        }
    }
}


text:
{% extends 'dashboard/layout.html' %}
{% load i18n %}
{% load currency_filters %}

{% block title %}
    {% trans "Edit weight band" %} |
    {{ band.method.name }} |
    {{ block.super }}
{% endblock %}

{% block breadcrumbs %}

            {% trans "Dashboard" %}

            {% trans "Shipping methods" %}

            {{ band.method.name }}

{% trans "Edit weight band" %}

{% endblock %}

{% block headertext %}
    {% trans "Edit weight band" %}
{% endblock %}

{% block dashboard_content %}

        <form method="post" class="form-stacked">
            {% csrf_token %}
            {% include "dashboard/partials/form_fields.html" with form=form %}
            {% block form_actions %}

                    <button class="btn btn-primary btn-lg" type="submit" data-loading-text="{% trans 'Saving...' %}">{% trans "Save" %}</button> {% trans "or" %}
                    {% trans "cancel" %}

            {% endblock form_actions %}
        </form>

{% endblock %}


text:
package com.ibasco.agql.protocols.valve.steam.webapi.pojos;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 *

 * "Acap" stands for Attribute Controlled Attached Particles. An object containing a list
 * of objects that describe the defined particle effects.
 *

 *
 * @author Rafael Luis Ibasco
 */
public class SteamEconSchemaAcap {

    /**
     * The name of the particle system.
     */
    private String system;

    /**
     * The effect's ID, referred to by the attached particle effect attribute.
     */
    private int id;

    /**
     * A boolean that indicates whether or not the effect is attached to the "root" bone.
     * That is the bone of the item with no parent bones used for rotation and animation calculations.
     */
    private boolean attach_to_rootbone;

    /**
     * (Optional) A string indicating where the effect is attached.
     */
    private String attachment;

    /**
     * The localized name of the effect.
     */
    private String name;

    /**
     *
Getter for the field system.

     *
     * @return a {@link java.lang.String} object
     */
    public String getSystem() {
        return system;
    }

    /**
     *
Setter for the field system.

     *
     * @param system
     *         a {@link java.lang.String} object
     */
    public void setSystem(String system) {
        this.system = system;
    }

    /**
     *
Getter for the field id.

     *
     * @return a int
     */
    public int getId() {
        return id;
    }

    /**
     *
Setter for the field id.

     *
     * @param id
     *         a int
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     *
isAttach_to_rootbone.

     *
     * @return a boolean
     */
    public boolean isAttach_to_rootbone() {
        return attach_to_rootbone;
    }

    /**
     *
Setter for the field attach_to_rootbone.

     *
     * @param attach_to_rootbone
     *         a boolean
     */
    public void setAttach_to_rootbone(boolean attach_to_rootbone) {
        this.attach_to_rootbone = attach_to_rootbone;
    }

    /**
     *
Getter for the field attachment.

     *
     * @return a {@link java.lang.String} object
     */
    public String getAttachment() {
        return attachment;
    }

    /**
     *
Setter for the field attachment.

     *
     * @param attachment
     *         a {@link java.lang.String} object
     */
    public void setAttachment(String attachment) {
        this.attachment = attachment;
    }

    /**
     *
Getter for the field name.

     *
     * @return a {@link java.lang.String} object
     */
    public String getName() {
        return name;
    }

    /**
     *
Setter for the field name.

     *
     * @param name
     *         a {@link java.lang.String} object
     */
    public void setName(String name) {
        this.name = name;
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.NO_CLASS_NAME_STYLE);
    }
}


text:
namespace test1 {
  int x; // expected-note {{previous definition is here}}
  static int y;
  void f() {} // expected-note {{previous definition is here}}

  extern "C" {
    extern int x; // expected-error {{declaration of 'x' has a different language linkage}}
    extern int y; // OK, has internal linkage, so no language linkage.
    void f(); // expected-error {{declaration of 'f' has a different language linkage}}
  }
}

// This is OK. Both test2_f don't have language linkage since they have
// internal linkage.
extern "C" {
  static void test2_f() {
  }
  static void test2_f(int x) {
  }
}

namespace test3 {
  extern "C" {
    namespace {
      extern int x2;
      void f2();
    }
  }
  namespace {
    int x2;
    void f2() {}
  }
}

namespace test4 {
  void dummy() {
    void Bar();
    class A {
      friend void Bar();
    };
  }
}

namespace test5 {
  static void g();
  void f()
  {
    void g();
  }
}

// pr14898
namespace test6 {
  template <class _Rp>
  class __attribute__ ((__visibility__("default"))) shared_future;
  template <class _Rp>
  class future {
    template <class> friend class shared_future;
    shared_future<_Rp> share();
  };
  template <class _Rp> future<_Rp>
  get_future();
  template <class _Rp>
  struct shared_future<_Rp&> {
    shared_future(future<_Rp&>&& __f); // expected-warning {{rvalue references are a C++11 extension}}
  };
  void f() {
    typedef int T;
    get_future<int>();
    typedef int& U;
    shared_future<int&> f1 = get_future<int&>();
  }
}

// This is OK. The variables have internal linkage and therefore no language
// linkage.
extern "C" {
  static int test7_x;
}
extern "C++" {
  extern int test7_x;
}
extern "C++" {
  static int test7_y;
}
extern "C" {
  extern int test7_y;
}
extern "C" { typedef int test7_F(); static test7_F test7_f; }
extern "C++" { extern test7_F test7_f; }

// FIXME: This should be invalid. The function has no language linkage, but
// the function type has, so this is redeclaring the function with a different
// type.
extern "C++" {
  static void test8_f();
}
extern "C" {
  extern void test8_f();
}
extern "C" {
  static void test8_g();
}
extern "C++" {
  extern void test8_g();
}

extern "C" {
  void __attribute__((overloadable)) test9_f(int c); // expected-note {{previous declaration is here}}
}
extern "C++" {
  void __attribute__((overloadable)) test9_f(int c); // expected-error {{declaration of 'test9_f' has a different language linkage}}
}

extern "C" {
  void __attribute__((overloadable)) test10_f(int);
  void __attribute__((overloadable)) test10_f(double);
}

extern "C" {
  void test11_f() {
    void  __attribute__((overloadable)) test11_g(int);
    void  __attribute__((overloadable)) test11_g(double);
  }
}

namespace test12 {
  const int n = 0;
  extern const int n;
  void f() {
    extern const int n;
  }
}

namespace test13 {
  static void a(void);
  extern void a();
  static void a(void) {}
}

namespace test14 {
  namespace {
    void a(void); // expected-note {{previous declaration is here}}
    static void a(void) {} // expected-error {{static declaration of 'a' follows non-static declaration}}
  }
}

namespace test15 {
  const int a = 5; // expected-note {{previous definition is here}}
  static const int a; // expected-error {{redefinition of 'a'}}
}

namespace test16 {
  extern "C" {
    class Foo {
      int x;
      friend int bar(Foo *y);
    };
    int bar(Foo *y) {
      return y->x;
    }
  }
}


text:
package ninja.metrics.graphite;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import ninja.lifecycle.Dispose;
import ninja.lifecycle.Start;
import ninja.metrics.MetricsService;
import ninja.utils.NinjaProperties;
import ninja.utils.TimeUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.graphite.GraphiteSender;
import com.codahale.metrics.graphite.PickledGraphite;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * Integration of Ninja Metrics with Graphite.
 *
 * @author James Moger
 */
@Singleton
public class NinjaGraphite {

    private final Logger log = LoggerFactory.getLogger(NinjaGraphite.class);

    private final NinjaProperties ninjaProperties;

    private final MetricsService metricsService;

    private GraphiteReporter reporter;

    @Inject
    public NinjaGraphite(NinjaProperties ninjaProperties,
                         MetricsService metricsService) {
        this.ninjaProperties = ninjaProperties;
        this.metricsService = metricsService;
    }

    @Start(order = 90)
    public void start() {

        if (ninjaProperties.getBooleanWithDefault("metrics.graphite.enabled",
                false)) {

            final String hostname = metricsService.getHostname();
            final String address = ninjaProperties
                    .getOrDie("metrics.graphite.address");
            final int port = ninjaProperties.getIntegerWithDefault(
                    "metrics.graphite.port", 2003);
            final boolean isPickled = ninjaProperties.getBooleanWithDefault(
                    "metrics.graphite.pickled", false);
            final String period = ninjaProperties.getWithDefault(
                    "metrics.graphite.period", "60s");
            final int delay = TimeUtil.parseDuration(period);
            final InetSocketAddress graphiteAddress = new InetSocketAddress(
                    address, port);

            final GraphiteSender sender;
            if (isPickled) {
                sender = new PickledGraphite(graphiteAddress);
            } else {
                sender = new Graphite(graphiteAddress);
            }

            reporter = GraphiteReporter
                    .forRegistry(metricsService.getMetricRegistry())
                    .prefixedWith(hostname).convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .filter(MetricFilter.ALL).build(sender);

            reporter.start(delay, TimeUnit.SECONDS);

            log.info(
                    "Started Graphite Metrics reporter for '{}', updating every {}",
                    hostname, period);

        }
    }

    @Dispose(order = 10)
    public void stop() {

        if (reporter != null) {

            reporter.stop();

            log.debug("Stopped Graphite Metrics reporter");
        }

    }
}


text:
import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptionsArgs, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Router } from '@angular/router';
import {AuthService} from './auth.service';
import {IError} from '../interfaces/error.interface';
import {ToastsManager} from 'ng2-toastr';

@Injectable()
export class RestService {

  public token = '';

  constructor(private _auth: AuthService, private _http: Http, private _router: Router, private _toast: ToastsManager) {
    this._auth.token.subscribe((token) => {
      this.token = token;
    });
  }

  /**
   * Abstracts HTTP POST
   * @param url {string}
   * @param body {any}
   * @returns {Promise<Observable<any>|T>}
   */
  post(url: string, body: any): Promise<any> {
    return this._http.post(url, body, this.buildOptions())
      .map(res => res.json())
      .toPromise()
      .catch(err => this.handleError(err));
  }

  /**
   * Abstracts HTTP GET
   * @param url {string}
   * @returns {Promise<Observable<any>|T>}
   */
  get(url: string): Promise<any> {
    return this._http.get(url, this.buildOptions())
      .map(res => res.json())
      .toPromise()
      .catch(err => this.handleError(err));
  }

  /**
   * Abstracts HTTP DELETE
   * @param url {string}
   * @returns {Promise<Observable<any>|T>}
   */
  delete(url: string): Promise<any> {
    return this._http.delete(url, this.buildOptions())
      .map(res => res.json())
      .toPromise()
      .catch(err => this.handleError(err));
  }

  /**
   * Abstracts HTTP PUT
   * @param url {string}
   * @param body {any}
   * @returns {Promise<Observable<any>|T>}
   */
  put(url: string, body: any): Promise<any> {
    return this._http.put(url, body, this.buildOptions())
      .map(res => res.json())
      .toPromise()
      .catch(err => this.handleError(err));
  }

  /**
   * Lets use set build options with auth token header on abstracted HTTP calls
   * @returns {{headers: Headers}} {RequestOptionsArgs}
   */

  buildOptions(): RequestOptionsArgs {
    const options = new RequestOptions();
    options.headers = new Headers();
    options.headers.append('Accept', 'application/json');
    options.headers.append('Authorization', '' + this.token);
    // console.log('this is token from bo2', 'Bearer ' + this.token);
    return options;
  }

  /**
   * Error handling for these calls
   * @param error {any}
   * @returns {any}
   */
  handleError(serverError: any): Promise<any> {
    const error: any = JSON.parse(serverError._body);
    this._toast.error(error.error);
    return Promise.reject(error);
  }
}


text:
package org.apache.camel.api.management.mbean;

import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedOperation;

public interface ManagedThroughputLoggerMBean extends ManagedProcessorMBean {

    @ManagedAttribute(description = "The received number of messages")
    int getReceivedCounter();

    @ManagedAttribute(description = "The average throughput")
    double getAverage();

    @ManagedAttribute(description = "The throughput rate")
    double getRate();

    @ManagedAttribute(description = "The last log message")
    String getLastLogMessage();

    @ManagedOperation(description = "Resets the throughput logger statistics")
    void resetThroughputLogger();

}


text:
/* @flow strict */

import React from 'react';
import { render } from '@testing-library/react';

import CustomCloseIcon from '../../bpk-component-icon/sm/close-circle';

import BpkCloseButton from './BpkCloseButton';

describe('BpkCloseButton', () => {
  it('should render correctly', () => {
    const { asFragment } = render(
      <BpkCloseButton label="Close" onClick={() => null} />,
    );
    expect(asFragment()).toMatchSnapshot();
  });

  it('should render correctly with a custom icon', () => {
    const { asFragment } = render(
      <BpkCloseButton
        label="Close"
        onClick={() => null}
        customIcon={CustomCloseIcon}
      />,
    );
    expect(asFragment()).toMatchSnapshot();
  });

  it('should render correctly with a custom className', () => {
    const { asFragment } = render(
      <BpkCloseButton
        label="Close"
        onClick={() => null}
        className="my-custom-classname"
      />,
    );
    expect(asFragment()).toMatchSnapshot();
  });
});


text:
package com.lonebytesoft.hamster.raytracing.util.math.equation;

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

public class LinearEquation {

    private final List<Double> coeffs;
    private final double free;

    public LinearEquation(final List<Double> coeffs, final double free) {
        this.coeffs = Collections.unmodifiableList(new ArrayList<>(coeffs));
        this.free = free;
    }

    public List<Double> getCoeffs() {
        return coeffs;
    }

    public double getFree() {
        return free;
    }

    @Override
    public String toString() {
        return "LinearEquation{" +
                "coeffs=" + coeffs +
                ", free=" + free +
                '}';
    }

}


text:
namespace EasyStorage
{
	/// <summary>
	/// The various states of the SaveDevice.
	/// </summary>
	internal enum SaveDevicePromptState
	{
		/// <summary>
		/// The SaveDevice is doing nothing.
		/// </summary>
		None,

		/// <summary>
		/// The SaveDevice needs to show the StorageDevice selector.
		/// </summary>
		ShowSelector,

		/// <summary>
		/// The SaveDevice needs to prompt the user because a
		/// StorageDevice selector was canceled.
		/// </summary>
		PromptForCanceled,

		/// <summary>
		/// The SaveDevice needs to force the user to choose a
		/// StorageDevice because a StorageDevice selector was canceled.
		/// </summary>
		ForceCanceledReselection,

		/// <summary>
		/// The SaveDevice needs to prompt the user because a
		/// StorageDevice was disconnected.
		/// </summary>
		PromptForDisconnected,

		/// <summary>
		/// The SaveDevice needs to force the user to choose a
		/// StorageDevice because a StorageDevice was disconnected.
		/// </summary>
		ForceDisconnectedReselection
	}
}


text:
package com.zebra.core.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 转换工具类 boolean string number
 * Created by lzy@js-dev.cn on 2016/10/26.
 */
public final class CastUtil {

	/**
	 * 转换为String
	 * @param obj
	 * @return
	 */
	public static String castString(Object obj){
		return CastUtil.castString(obj,"");
	}

	/**
	 * 转换为String (提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String castString(Object obj,String defaultValue){
		return obj !=null ? String.valueOf(obj.toString()) : defaultValue;
	}

	/**
	 * 转换成int
	 * @param obj
	 * @return
	 */
	public static int castInt(Object obj){
		return CastUtil.castInt(obj,0);
	}

	/**
	 * 转换成int (提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	private static int castInt(Object obj, int defaultValue) {
		int value = defaultValue;
		if(obj != null) {
			String strValue = castString(obj);
			if(StringUtils.isNotBlank(strValue)){
				try{
					value = Integer.parseInt(strValue);
				}catch(NumberFormatException e){
					value = defaultValue;
				}
			}
		}
		return value;
	}

	/**
	 * 转换成Long
	 * @param obj
	 * @return
	 */
	public static long castLong(Object obj){
		return CastUtil.castLong(obj,0);
	}

	/**
	 * 转换成Long (提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	private static long castLong(Object obj, long defaultValue) {
		long value = defaultValue;
		if( obj != null) {
			String strValue = castString(obj);
			if(StringUtils.isNotBlank(strValue)){
				try{
					value = Long.parseLong(strValue);
				}catch (NumberFormatException e){
					value = defaultValue;
				}
			}
		}
		return value;
	}

	/**
	 * 转换为Double
	 * @param obj
	 * @return
	 */
	public static double castDouble(Object obj){
		return CastUtil.castDouble(obj,0);
	}

	/**
	 * 转换为Double (提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	private static double castDouble(Object obj, double defaultValue) {
		double value = defaultValue;
		if( obj != null){
			String strValue = castString(obj);
			if(StringUtils.isNotBlank(strValue)) {
				try {
					value = Double.parseDouble(strValue);
				}catch (NumberFormatException e){
					value = defaultValue;
				}
			}
		}
		return value;
	}

}


text:
@class ZXTweetModel;

@interface ZXTweetCell : UITableViewCell
@property (nonatomic,strong) UILabel        *titleLabel;
@property (nonatomic,strong) UILabel        *contentLabel;
@property (nonatomic,strong) UILabel        *nowDateLabel;
@property (nonatomic,strong) UILabel        *commentLabel;
@property (nonatomic,strong) UIImageView    *iconView;
@property (nonatomic,strong) UIImageView    *smallView;
@property (nonatomic,strong) UIImageView    *commentView;

@property (nonatomic,strong) ZXTweetModel    *myModel;

+(ZXTweetCell *)cellWithTableView:(UITableView *)tableView;

-(void)setModel:(ZXTweetModel *)model andShow:(BOOL)isShouldShow;
@end


text:
#include "include/sbsa_avs_val.h"
#include "include/sbsa_avs_gic.h"
#include "include/sbsa_avs_gic_support.h"
#include "include/sbsa_avs_pe.h"
#include "gic_v3.h"
#include "gic.h"
#include "sbsa_exception.h"

/**
  @brief  API used to clear espi interrupt
  @param  interrupt
  @return none
**/
void v3_clear_extended_spi_interrupt(uint32_t int_id)
{
  uint32_t reg_offset = (int_id - EXTENDED_SPI_START_INTID) / 32;
  uint32_t reg_shift  = (int_id - EXTENDED_SPI_START_INTID) % 32;

  val_mmio_write(val_get_gicd_base() + GICD_ICPENDRE0 + (4 * reg_offset), (1 << reg_shift));
  val_mmio_write(val_get_gicd_base() + GICD_ICACTIVERE0 + (4 * reg_offset), (1 << reg_shift));
}

/**
  @brief  checks if given int id is espi
  @param  int_id
  @return true if ESPI
**/
uint32_t
v3_is_extended_spi(uint32_t int_id)
{
  if (int_id >= EXTENDED_SPI_START_INTID && int_id <= val_sbsa_gic_max_espi_val())
      return 1;
  else
      return 0;
}

/**
  @brief  checks if given int id is eppi
  @param  int_id
  @return true if EPPI
**/
uint32_t
v3_is_extended_ppi(uint32_t int_id)
{
  if (int_id >= EXTENDED_PPI_START_INTID && int_id <= val_sbsa_gic_max_eppi_val())
      return 1;
  else
      return 0;
}

/**
  @brief  Disables the interrupt source
  @param  interrupt id
  @return none
**/
void
v3_disable_extended_interrupt_source(uint32_t int_id)
{
  uint32_t                regOffset;
  uint32_t                regShift;
  uint64_t                cpuRd_base;

  if (v3_is_extended_spi(int_id)) {
      /* Calculate register offset and bit position */
      regOffset = (int_id - EXTENDED_SPI_START_INTID) / 32;
      regShift = (int_id - EXTENDED_SPI_START_INTID) % 32;
      val_mmio_write(val_get_gicd_base() + GICD_ICENABLERE + (4 * regOffset), 1 << regShift);
  } else {
      /* Calculate register offset and bit position */
      regOffset = (int_id - EXTENDED_PPI_REG_OFFSET) / 32;
      regShift = (int_id - EXTENDED_PPI_REG_OFFSET) % 32;
      cpuRd_base = v3_get_pe_gicr_base();
      if (cpuRd_base == 0) {
        return;
      }
      val_mmio_write(cpuRd_base + GICR_CTLR_FRAME_SIZE + GICR_ICENABLER + (4 * regOffset),
                   1 << regShift);
  }
}

/**
  @brief  Enables the interrupt source
  @param  interrupt id
  @return none
**/
void
v3_enable_extended_interrupt_source(uint32_t int_id)
{
  uint32_t                regOffset;
  uint32_t                regShift;
  uint64_t                cpuRd_base;

  if (v3_is_extended_spi(int_id)) {
      /* Calculate register offset and bit position */
      regOffset = (int_id - EXTENDED_SPI_START_INTID) / 32;
      regShift = (int_id - EXTENDED_SPI_START_INTID) % 32;
      val_mmio_write(val_get_gicd_base() + GICD_ICENABLERE + (4 * regOffset), 1 << regShift);
  } else {
      /* Calculate register offset and bit position */
      regOffset = (int_id - EXTENDED_PPI_REG_OFFSET) / 32;
      regShift = (int_id - EXTENDED_PPI_REG_OFFSET) % 32;
      cpuRd_base = v3_get_pe_gicr_base();
      if (cpuRd_base == 0) {
        return;
      }
      val_mmio_write(cpuRd_base + GICR_CTLR_FRAME_SIZE + GICR_ISENABLER + (4 * regOffset),
                   1 << regShift);
  }
}

/**
  @brief  Sets interrupt priority
  @param  interrupt id
  @param  priority
  @return none
**/
void
v3_set_extended_interrupt_priority(uint32_t int_id, uint32_t priority)
{
  uint32_t                regOffset;
  uint32_t                regShift;
  uint64_t                cpuRd_base;

  if (v3_is_extended_spi(int_id)) {
      /* Calculate register offset and bit position */
      regOffset = (int_id - EXTENDED_SPI_START_INTID) / 4;
      regShift = ((int_id - EXTENDED_SPI_START_INTID) % 4) * 8;

      val_mmio_write(val_get_gicd_base() + GICD_IPRIORITYRE + (4 * regOffset),
                    (val_mmio_read(val_get_gicd_base() + GICD_IPRIORITYRE + (4 * regOffset)) &
                     ~(0xff << regShift)) | priority << regShift);
  } else {
     /* Calculate register offset and bit position */
    regOffset = (int_id - EXTENDED_PPI_REG_OFFSET) / 4;
    regShift = ((int_id - EXTENDED_PPI_REG_OFFSET) % 4) * 8;

    cpuRd_base = v3_get_pe_gicr_base();
    if (cpuRd_base == 0) {
      return;
    }
    val_mmio_write(cpuRd_base + GICR_IPRIORITYR + (4 * regOffset),
                  (val_mmio_read(cpuRd_base + GICR_IPRIORITYR + (4 * regOffset)) &
                   ~(0xff << regShift)) | priority << regShift);
  }
}

/**
  @brief  Route interrupt to primary PE
  @param  interrupt id
  @return none
**/
void
v3_route_extended_interrupt(uint32_t int_id)
{
  uint64_t   gicd_base;
  uint64_t   cpuTarget;
  uint64_t   Mpidr;

  /* Get the distributor base */
  gicd_base = val_get_gicd_base();

  Mpidr = ArmReadMpidr();
  cpuTarget = Mpidr & (PE_AFF0 | PE_AFF1 | PE_AFF2 | PE_AFF3);

  val_mmio_write64(gicd_base + GICD_IROUTERn + (int_id * 8), cpuTarget);
}

/**
  @brief  Initializes the GIC v3 Extended Interrupts
  @param  none
  @return init success or failure
**/
void
v3_extended_init(void)
{
  uint32_t   max_num_espi_interrupts;
  uint32_t   max_num_eppi_interrupts;
  uint32_t   index;

  /* Get the max interrupt */
  max_num_espi_interrupts = val_sbsa_gic_max_espi_val();
  max_num_eppi_interrupts = val_sbsa_gic_max_eppi_val();

  val_print(AVS_PRINT_DEBUG, "\n GIC_INIT: Extended SPI Interrupts %d\n", max_num_espi_interrupts);
  val_print(AVS_PRINT_DEBUG, "\n GIC_INIT: Extended PPI Interrupts %d\n", max_num_eppi_interrupts);

  /* Disable all ESPI interrupt */
  for (index = EXTENDED_SPI_START_INTID; index <= max_num_espi_interrupts; index++) {
      v3_disable_extended_interrupt_source(index);
  }

  /* Disable all EPPI interrupt */
  for (index = EXTENDED_PPI_START_INTID; index <= max_num_eppi_interrupts; index++) {
      v3_disable_extended_interrupt_source(index);
  }

  /* Set default for ESPI priority */
  for (index = EXTENDED_SPI_START_INTID; index <= max_num_espi_interrupts; index++) {
      v3_set_extended_interrupt_priority(index, GIC_DEFAULT_PRIORITY);
  }

  /* Set default for EPPI priority */
  for (index = EXTENDED_PPI_START_INTID; index <= max_num_eppi_interrupts; index++) {
      v3_set_extended_interrupt_priority(index, GIC_DEFAULT_PRIORITY);
  }

  /* Route ESPI to primary PE */
  for (index = EXTENDED_SPI_START_INTID; index <= (max_num_espi_interrupts); index++) {
      v3_route_extended_interrupt(index);
  }

}


text:
package org.apereo.cas.adaptors.x509.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.apereo.cas.adaptors.x509.authentication.principal.X509CertificateCredential;
import org.apereo.cas.util.EncodingUtils;
import org.apereo.cas.util.crypto.CertUtils;
import org.springframework.core.io.InputStreamResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * This is {@link X509CertificateCredentialJsonDeserializer}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class X509CertificateCredentialJsonDeserializer extends JsonDeserializer<X509CertificateCredential> {

    @Override
    public X509CertificateCredential deserialize(final JsonParser jp,
                                                 final DeserializationContext deserializationContext)
            throws IOException {
        final ObjectCodec oc = jp.getCodec();
        final JsonNode node = oc.readTree(jp);

        final List<X509Certificate> certs = new ArrayList<>();
        node.findValues("certificates").forEach(n -> {
            final String cert = n.get(0).textValue();
            final byte[] data = EncodingUtils.decodeBase64(cert);
            certs.add(CertUtils.readCertificate(new InputStreamResource(new ByteArrayInputStream(data))));
        });
        final X509CertificateCredential c = new X509CertificateCredential(certs.toArray(new X509Certificate[] {}));
        return c;
    }
}


text:
using testing::_;
using testing::DoAll;
using testing::Mock;
using testing::SaveArg;

namespace remoting {
namespace protocol {

namespace {
const char kTestMessage1[] = "Message1";
const char kTestMessage2[] = "Message2";

ACTION(CallDoneTask) {
  arg1.Run();
}
}

class MockMessageReceivedCallback {
 public:
  MOCK_METHOD2(OnMessage, void(CompoundBuffer*, const base::Closure&));
};

class MessageReaderTest : public testing::Test {
 public:
  MessageReaderTest()
      : other_thread_("SecondTestThread"),
        run_task_finished_(false, false) {
  }

  void RunDoneTaskOnOtherThread(CompoundBuffer* buffer,
                                const base::Closure& done_task) {
    other_thread_.message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&MessageReaderTest::RunAndDeleteTask,
                   base::Unretained(this), done_task));
  }

 protected:
  virtual void SetUp() {
    reader_ = new MessageReader();
  }

  void InitReader() {
    reader_->Init(&socket_, base::Bind(
        &MockMessageReceivedCallback::OnMessage, base::Unretained(&callback_)));
  }

  void AddMessage(const std::string& message) {
    std::string data = std::string(4, ' ') + message;
    talk_base::SetBE32(const_cast<char*>(data.data()), message.size());

    socket_.AppendInputData(std::vector<char>(data.begin(), data.end()));
  }

  bool CompareResult(CompoundBuffer* buffer, const std::string& expected) {
    std::string result(buffer->total_bytes(), ' ');
    buffer->CopyTo(const_cast<char*>(result.data()), result.size());
    return result == expected;
  }

  void RunAndDeleteTask(const base::Closure& task) {
    task.Run();
    run_task_finished_.Signal();
  }

  MessageLoop message_loop_;
  base::Thread other_thread_;
  base::WaitableEvent run_task_finished_;
  scoped_refptr<MessageReader> reader_;
  FakeSocket socket_;
  MockMessageReceivedCallback callback_;
};

// Receive one message and process it with delay
TEST_F(MessageReaderTest, OneMessage_Delay) {
  CompoundBuffer* buffer;
  base::Closure done_task;

  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(DoAll(SaveArg<0>(&buffer),
                      SaveArg<1>(&done_task)));

  InitReader();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(buffer, kTestMessage1));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task);

  EXPECT_TRUE(socket_.read_pending());
}

// Receive one message and process it instantly.
TEST_F(MessageReaderTest, OneMessage_Instant) {
  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(CallDoneTask());

  InitReader();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in one packet.
TEST_F(MessageReaderTest, TwoMessages_Together) {
  CompoundBuffer* buffer1;
  base::Closure done_task1;
  CompoundBuffer* buffer2;
  base::Closure done_task2;

  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(2)
      .WillOnce(DoAll(SaveArg<0>(&buffer1),
                      SaveArg<1>(&done_task1)))
      .WillOnce(DoAll(SaveArg<0>(&buffer2),
                      SaveArg<1>(&done_task2)));

  InitReader();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(buffer1, kTestMessage1));
  EXPECT_TRUE(CompareResult(buffer2, kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task1);

  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task2);

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in one packet, and process the first one
// instantly.
TEST_F(MessageReaderTest, TwoMessages_Instant) {
  CompoundBuffer* buffer2;
  base::Closure done_task2;

  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(2)
      .WillOnce(CallDoneTask())
      .WillOnce(DoAll(SaveArg<0>(&buffer2),
                      SaveArg<1>(&done_task2)));

  InitReader();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(buffer2, kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the second message.
  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task2);

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in one packet, and process both of them
// instantly.
TEST_F(MessageReaderTest, TwoMessages_Instant2) {
  AddMessage(kTestMessage1);
  AddMessage(kTestMessage2);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(2)
      .WillOnce(CallDoneTask())
      .WillOnce(CallDoneTask());

  InitReader();

  EXPECT_TRUE(socket_.read_pending());
}

// Receive two messages in separate packets.
TEST_F(MessageReaderTest, TwoMessages_Separately) {
  CompoundBuffer* buffer;
  base::Closure done_task;

  AddMessage(kTestMessage1);

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(DoAll(SaveArg<0>(&buffer),
                      SaveArg<1>(&done_task)));

  InitReader();

  Mock::VerifyAndClearExpectations(&callback_);
  Mock::VerifyAndClearExpectations(&socket_);

  EXPECT_TRUE(CompareResult(buffer, kTestMessage1));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task);

  EXPECT_TRUE(socket_.read_pending());

  // Write another message and verify that we receive it.
  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(DoAll(SaveArg<0>(&buffer),
                      SaveArg<1>(&done_task)));
  AddMessage(kTestMessage2);

  EXPECT_TRUE(CompareResult(buffer, kTestMessage2));

  // Verify that the reader starts reading again only after we've
  // finished processing the previous message.
  EXPECT_FALSE(socket_.read_pending());

  RunAndDeleteTask(done_task);

  EXPECT_TRUE(socket_.read_pending());
}

// Verify that socket operations occur on same thread, even when the OnMessage()
// callback triggers |done_task| to run on a different thread.
TEST_F(MessageReaderTest, UseSocketOnCorrectThread) {

  AddMessage(kTestMessage1);
  other_thread_.Start();

  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(Invoke(this, &MessageReaderTest::RunDoneTaskOnOtherThread));

  InitReader();

  run_task_finished_.Wait();
  message_loop_.RunAllPending();

  // Write another message and verify that we receive it.
  CompoundBuffer* buffer;
  base::Closure done_task;
  EXPECT_CALL(callback_, OnMessage(_, _))
      .Times(1)
      .WillOnce(DoAll(SaveArg<0>(&buffer),
                      SaveArg<1>(&done_task)));
  AddMessage(kTestMessage2);
  EXPECT_TRUE(CompareResult(buffer, kTestMessage2));

  RunAndDeleteTask(done_task);
}

}  // namespace protocol
}  // namespace remoting


text:
package com.csyangchsh.hibernate.demo;

import com.csyangchsh.hibernate.demo.entity.Album;
import com.csyangchsh.hibernate.demo.entity.Artist;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import java.util.List;

/**
 * Query cache and second level cache demo
 *
 * Enable query cache and second level cache
 * timeToLiveSeconds="5" in ehcache.xml
 *
 * Query cache hitting but second level cache missing, hibernate will generate db query for each entity.
 *
 * @Author csyangchsh
 * Date: 14/8/1
 */
public class Demo {

    protected final SessionFactory sessionFactory;

    public Demo() {
        final Configuration configuration = new Configuration();
        configuration.addAnnotatedClass( Artist.class );
        configuration.addAnnotatedClass( Album.class );

        sessionFactory = configuration.buildSessionFactory(
                new StandardServiceRegistryBuilder().build());
    }

    protected Session openSession() {
        return sessionFactory.openSession();
    }

    public void printStats() {

        System.out.println("query cache put count: " + sessionFactory.getStatistics().getQueryCachePutCount());
        System.out.println("query cache hit count: " + sessionFactory.getStatistics().getQueryCacheHitCount());
        System.out.println("query cache miss count: " + sessionFactory.getStatistics().getQueryCacheMissCount());
        System.out.println("second level cache put count: " + sessionFactory.getStatistics().getSecondLevelCachePutCount());
        System.out.println("second level cache hit count: " + sessionFactory.getStatistics().getSecondLevelCacheHitCount());
        System.out.println("second level cache miss count: " + sessionFactory.getStatistics().getSecondLevelCacheMissCount());
    }

    public List<Artist> getArtists() {
        final Session s = openSession();
        s.getTransaction().begin();
        final Query q = s.createQuery("FROM Artist");
        q.setCacheable( true );
        final List<Artist> artists = q.list();
        s.getTransaction().commit();
        return artists;
    }

    public static void main(String[] args) throws InterruptedException {
        final Demo demo = new Demo();

        System.out.println("GET Artists, ATTEMPT #1");
        // DB hit
        List<Artist> artists = demo.getArtists();
        demo.printStats();

        System.out.println("GET Artists, ATTEMPT #2");
        // query cache hit
        artists = demo.getArtists();
        demo.printStats();

        // timeToLiveSeconds="5" in ehcache.xml
        Thread.sleep(5000);
        System.out.println("GET Artists, ATTEMPT #3");
        // query cache hit, second level cache missing
        artists = demo.getArtists();
        demo.printStats();
    }
}


text:
package org.arakhne.afc.inputoutput.filetype;

import java.io.InputStream;
import java.net.URL;
import javax.activation.MimeType;

import org.arakhne.afc.inputoutput.mime.MimeName;
import org.arakhne.afc.vmutil.FileSystem;

/** This class defines a set of informations that could distinguish
 * a file content from another one. It is also known as Magic Number
 * on several operating systems.
 *
 *
This magic number supports Jar files (ie Zip file with manifest).
 * For general zipped file, please see {@link ZipMagicNumber}.
 * For zip archive of files, please see {@link ZipArchiveMagicNumber}.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 14.0
 * @see ZipMagicNumber
 * @see ZipArchiveMagicNumber
 */
public class JarMagicNumber extends MagicNumber {

	private static final String METAINF_PATH = "META-INF/MANIFEST.MF"; //$NON-NLS-1$

	/** Constructor.
	 * @param mimeType is the MIME type associated to this magic number.
	 */
	public JarMagicNumber(MimeType mimeType) {
		super(mimeType, MimeName.MIME_ZIP.toMimeType());
	}

	/** Constructor.
	 * @param mimeType is the MIME type associated to this magic number.
	 * @param formatVersion is the version of the supported format.
	 */
	public JarMagicNumber(MimeType mimeType, String formatVersion) {
		super(mimeType, formatVersion, MimeName.MIME_ZIP.toMimeType());
	}

	@Override
	protected final boolean isContentType(MagicNumberStream stream) {
		try {
			URL url = stream.getURL();
			url = FileSystem.toJarURL(url, METAINF_PATH);
			try (InputStream manifest = url.openStream()) {
				return isManifestMatch(manifest);
			}
		} catch (Exception e) {
			return false;
		}
	}

	/** Invoked to test the content of the Jar file manifest.
	 *
	 * @param manifestContent is the content of the manifest
	 * @return true if the manifest is matching, otherwise false
	 */
	public boolean isManifestMatch(InputStream manifestContent) {
		return true;
	}

}


text:
from torch.utils.ffi import _wrap_function
from horovod.common import get_ext_suffix as _get_ext_suffix
from ._mpi_lib import ffi as _ffi
import os as _os

# Make sure to preserve this code to load library with RTLD_GLOBAL,
# otherwise it will get unloaded.
_lib = _ffi.dlopen(_os.path.join(_os.path.dirname(__file__),
                                '_mpi_lib' + _get_ext_suffix()),
                   _ffi.RTLD_GLOBAL)

__all__ = []
def _import_symbols(locals):
    for symbol in dir(_lib):
        fn = getattr(_lib, symbol)
        if callable(fn):
            locals[symbol] = _wrap_function(fn, _ffi)
        else:
            locals[symbol] = fn
        __all__.append(symbol)

_import_symbols(locals())


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>_variables.scss</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../css/github.css" type="text/css" media="screen" />

            _variables.scss

app/assets/stylesheets/bitters/_variables.scss

Last modified: 2015-05-17 11:24:43 -0500

// Typography $sans-serif: $helvetica; $serif: $georgia; $base-font-family:
$sans-serif; $header-font-family: $base-font-family;

// Font Sizes $base-font-size: 1em; $h1-font-size: $base-font-size * 1.5;
$h2-font-size: $base-font-size * 1.25; $h3-font-size: $base-font-size *
1.25; $h4-font-size: $base-font-size; $h5-font-size: $base-font-size ;
$h6-font-size: $base-font-size;

// Line height $base-line-height: 1.5; $header-line-height: 1.25;

// Other Sizes $base-border-radius: 3px; $base-spacing: $base-line-height *
1em; $base-z-index: 0;

// Colors $blue: #477DCA; $dark-gray: #333; $medium-gray: #999;
$light-gray: #DDD; $light-red: #FBE3E4; $light-yellow: #FFF6BF;
$light-green: #E6EFC2; $light-blue: #CAE1FF;

// Background Color $base-background-color: $light-blue;

// Font Colors $base-font-color: $dark-gray; $base-accent-color: $blue;

// Link Colors $base-link-color: $base-accent-color; $hover-link-color:
darken($base-accent-color, 15); $base-button-color: $base-link-color;
$hover-button-color: $hover-link-color;

// Flash Colors $alert-color: $light-yellow; $error-color: $light-red;
$notice-color: lighten($base-accent-color, 40); $success-color:
$light-green;

// Border color $base-border-color: $light-gray; $base-border: 1px solid
$base-border-color;

// Forms $form-border-color: $base-border-color; $form-border-color-hover:
darken($base-border-color, 10); $form-border-color-focus:
$base-accent-color; $form-border-radius: $base-border-radius;
$form-box-shadow: inset 0 1px 3px rgba(black,0.06); $form-box-shadow-focus:
$form-box-shadow, 0 0 5px rgba(darken($form-border-color-focus, 5), 0.7);
$form-font-size: $base-font-size; $form-font-family: $base-font-family;


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using System.Drawing;
using System.Drawing.Drawing2D;

using RMC;

namespace HersheyLib
{
    public class HersheyFont
    {
        public HersheyChar[] CharData;

        public int[] Translation;
        public bool NewStyle = false;
        public List<string> fileData;

        /// <summary>
        ///
        /// </summary>
        public HersheyFont()
        {
            Translation = new int[256];
            CharData = new HersheyChar[256];
        }

        public HersheyFont LoadFromCsv(string Filename)
        {
            HersheyFont result = new HersheyFont();

            fileData = ReadFileStrings(Filename);

            for (int index = 0; index < 256; index++)
            {
                CharData[index] = new HersheyChar();

                if (NewStyle)
                {
                    CharData[index].ParseCsvCharacterData(fileData[index]);
                }
                else if (index < 128)
                {
                    int HersheyCharNum = Translation[index];

                    if (HersheyCharNum != -1)
                        CharData[index].ParseCsvCharacterData(fileData[HersheyCharNum]);
                }
            }

            return result;
        }

        public HersheyFont SaveToCsv(string Filename)
        {
            HersheyFont result = new HersheyFont();

            List<string> data = new List<string>() ;

            for (int index = 0; index < 256; index++)
            {
                string line = CharData[index].ToString();
                data.Add(line);
            }
            WriteFileStrings(Filename, data);

            return result;
        }

        public HersheyFont LoadTranslationCsv(string Filename, int FontNumber)
        {
            HersheyFont result = new HersheyFont();

            fileData = ReadFileStrings(Filename);

            bool first = true;
            foreach (string line in fileData)
            {
                if (!first)
                {
                    int AsciiCharNum = Convert.ToInt32(StringUtils.GetDsvField(line, ",", 0));
                    int HersheyCharNum = Convert.ToInt32(StringUtils.GetDsvField(line, ",", 2+FontNumber));
                    Translation[AsciiCharNum] = HersheyCharNum;
                }

                first = false;
            }

            return result;
        }

        public void SaveToCs (string Filename)
        {
            List<string> lines = new List<string>();

            lines.Add("namespace HersheyData");
            lines.Add("// This file is auto-generated");
            lines.Add("{");
            lines.Add("  public class MyFont");
            lines.Add("  {");
            lines.Add("    public static int [] Data = new int [] {");
            for (int index = 0; index < 256; index++)
            {
                if (CharData[index].Paths.Count != 0)
                    CharData[index].SaveAsCs(lines, index);
            }
            lines.Add("      -1, 0");
            lines.Add("    };");
            lines.Add("  }");
            lines.Add("}");

            WriteFileStrings(Filename, lines);
        }

        public void CreateFont(int[] Data)
        {
            int index = 0;
            while (index < Data.Length)
            {
                HersheyChar ch = new HersheyChar();

                int CharNum = Data[index++];
                int NumPaths = Data[index++];

                if (CharNum < 0)
                    return;

                ch.MinExtent.X = Data[index++];
                ch.MaxExtent.X = Data[index++];

                for (int pathnum = 0; pathnum < NumPaths; pathnum++)
                {
                    int NumPoints = Data[index++];
                    VectorPath path = new VectorPath();
                    for (int PointNum = 0; PointNum < NumPoints; PointNum++)
                    {
                        PointF p = new PointF();
                        p.X = Data[index++];
                        p.Y = Data[index++];
                        path.Points.Add(p);
                    }
                    ch.Paths.Add(path);
                }

                CharData[CharNum] = ch;
            }
        }

        public static List<string> ReadFileStrings(string Filename)
        {
            // create reader & open file
            TextReader tr = new StreamReader(Filename);
            List<string> result = new List<string>();

            string line = tr.ReadLine();

            while (line != null)
            {
                result.Add(line);
                line = tr.ReadLine();
            }

            // close the stream
            tr.Close();

            return result;
        }

        public static bool WriteFileStrings(string Filename, List<string> Data)
        {
            // create reader & open file
            TextWriter tr = new StreamWriter(Filename);

            foreach (string line in Data)
            {
                tr.WriteLine(line);
            }

            // close the stream
            tr.Close();

            return true;
        }

    }
}


text:
const Vinyl = require('vinyl');
const PluginError = require('plugin-error');
const path = require('path');
const MessageFormat = require('messageformat');
const EOL = require('os').EOL;
const through = require('through2');

module.exports = function (options) {
	let  messages = {};
	let resultFile = null;

	options = options || {};

	if (!options.locale) {
		throw new PluginError('gulp-messageformat', 'Options `locale` is required.');
	}

	options.namespace = options.namespace || 'i18n';
	const mf = new MessageFormat(options.locale.trim());

	function parse(file, encoding, next) {

		if (file.isNull()) {
			this.push(file);
			next();
			return;
		}

		if (file.isStream()) {
			next(new PluginError('gulp-messageformat', 'Streaming not supported' ,{
				fileName: file.path,
				showStack: false
			}));
			return;
		}

		if (!resultFile) {
			resultFile = new Vinyl({
				path: path.join(file.base, options.locale + '.js'),
				base: file.base,
				cwd: file.cwd,
				contents: new Buffer('')
			});
		}

		try {
			let input = JSON.parse(file.contents.toString());
			var fileName = path.basename(file.path, path.extname(file.path));
			Object.assign(messages, { [fileName]: input });
		} catch (errs) {
			var message = '';

			if (errs.join) {
				message = errs.join('\n');
			} else {
				message = errs.name + ': ' +  errs.message + '. File: ' + file.relative;
			}

			this.emit('error', new PluginError('gulp-messageformat', message, {
				fileName: file.path,
				showStack: false
			}));
		}

		next();
	}

	function flush(cb) {
		if(!resultFile) {
			cb();
			return;
		}

		let result = mf.compile(messages).toString(options.namespace);
		resultFile.contents = new Buffer(result);

		this.push(resultFile);

		cb();
	}

	return through.obj(parse, flush);

};


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message/extract' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'All notifications have been deleted.' => 'Tutte le notifiche sono state cancellate.',
    'All notifications have been marked as read.' => 'Tutte le notifiche sono state segnate come lette.',
    'Delete all' => 'Cancella tutto',
    'Mark all as read' => 'Segna tutto come letto',
    'Mark as read' => 'Segna come letto',
    'Notifications' => 'Notifiche',
    'Read' => 'Leggi',
    'There are no notifications to show' => 'Nessuna notifica da mostrare',
    'View all' => 'Vedi tutto',
    'a moment' => 'un momento',
    'ago' => 'fa',
    '{n, plural, one{one day} other{# days}}' => '{n, plural, one{un giorno} other{# giorni}}',
    '{n, plural, one{one hour} other{# hours}}' => '{n, plural, one{un ora} other{# ore}}',
    '{n, plural, one{one minute} other{# minutes}}' => '{n, plural, one{un minuto} other{# minuti}}',
    '{n, plural, one{one month} other{# months}}' => '{n, plural, one{un mese} other{# mesi}}',
    '{n, plural, one{one second} other{# seconds}}' => '{n, plural, one{un secondo} other{# secondi}}',
    '{n, plural, one{one week} other{# weeks}}' => '{n, plural, one{una settimana} other{# settimane}}',
    '{n, plural, one{one year} other{# years}}' => '{n, plural, one{un anno} other{# anni}}',
];


text:
package org.apache.hadoop.hbase;

/**
 * Monitor the resources. use by the tests All resources in {@link ResourceCheckerJUnitListener}
 *  plus the number of connection.
 */
public class ServerResourceCheckerJUnitListener extends ResourceCheckerJUnitListener {
}


text:
angular.module('ngCordova.plugins.nativeAudio', [])

  .factory('$cordovaNativeAudio', ['$q', '$window', function ($q, $window) {

    return {
      preloadSimple: function (id, assetPath) {
        var q = $q.defer();
        $window.plugins.NativeAudio.preloadSimple(id, assetPath,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      },

      preloadComplex: function (id, assetPath, volume, voices) {
        var q = $q.defer();
        $window.plugins.NativeAudio.preloadComplex(id, assetPath, volume, voices,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      },

      play: function (id, completeCallback) {
        var q = $q.defer();
        $window.plugins.NativeAudio.play(id, completeCallback,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      },

      stop: function (id) {
        var q = $q.defer();
        $window.plugins.NativeAudio.stop(id,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );
        return q.promise;
      },

      loop: function (id) {
        var q = $q.defer();
        $window.plugins.NativeAudio.loop(id,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      },

      unload: function (id) {
        var q = $q.defer();
        $window.plugins.NativeAudio.unload(id,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      },

      setVolumeForComplexAsset: function (id, volume) {
        var q = $q.defer();
        $window.plugins.NativeAudio.setVolumeForComplexAsset(id, volume,
          function (result) {
            q.resolve(result)
          },
          function (err) {
            q.reject(err);
          }
        );

        return q.promise;
      }
    }
  }]);