text:
package mchenys.net.csdn.blog.coolweather;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.RouteNode;
import com.baidu.mapapi.search.core.RouteStep;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteLine;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.WalkingRouteLine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import mchenys.net.csdn.blog.coolweather.adapter.RouteStepAdapter;
import mchenys.net.csdn.blog.coolweather.adapter.RouteType;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.BikingRouteOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.BusLineOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.DrivingRouteOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.MassTransitRouteOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.PoiOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.TransitRouteOverlay;
import mchenys.net.csdn.blog.coolweather.mapapi.overlayutil.WalkingRouteOverlay;

/**
 * Created by mChenys on 2016/12/24.
 */
public class BDMapActivity extends AppCompatActivity {
    private static final String TAG = "BDMapActivity";
    private static final int REQ_SEARCH_BUSLINE = 200;
    private static final int REQ_SEARCH_ROUTE = 100;
    private MapView mMapView;
    private boolean isFirstLoc;
    private ImageButton mRouteIb;
    private String startCityName, startPlaceName, mStartNodeName, mEndNodeName;
    private LinearLayout mStepLayout;//显示所有路线步骤的布局
    private FrameLayout mModeLayout;//地图模式(普通,跟随,罗盘)跟布局
    private TextView mStepDescTv;
    private ListView mRouteStepLv;//显示节点的ListView
    private int mContentHeight;
    private FrameLayout mContentFl;
    private ImageView mStepBackIv;
    private ImageButton mBackIb, mSettingIb;
    private TextView mBusSearchTv;
    private LinearLayout mTitleBarLl;
    private DrawerLayout mDrawerLayout;
    private LinearLayout mWXLayerLl, m2DLayerLl, m3DLayerLl;
    private CheckBox mPersonalMapCb, mRealRouteCb, mHotMapCb, mModeCb;
    private ImageView mNoModeIv;
    private LocationClient mLocationClient;
    private BaiduMap mBaiduMap;
    private GeoCoder mGeoCoder;
    private BusLineResult mBusLineResult;
    private PoiSearch mPoiSearch;

    private LatLng mStartLatLng, mEndLatLng;
    private int nowSearchType = -1;
    private boolean isOpenLocation;//是否开启自动定位
    private ArrayList<? extends RouteLine> mCurrRouteLineList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMapCustomFile(this);
        setContentView(R.layout.activity_bdmap);
        initView();
        requestLocation();
        initListener();
        setLayerByPosition();
        setMapSettingByLastSave();
    }

    private void initView() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mContentFl = (FrameLayout) findViewById(R.id.fl_content);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBusSearchTv = (TextView) findViewById(R.id.tv_bus_search);
        mBackIb = (ImageButton) findViewById(R.id.ib_back);
        mSettingIb = (ImageButton) findViewById(R.id.ib_setting);
        mTitleBarLl = (LinearLayout) findViewById(R.id.ll_titlebar);
        mStepLayout = (LinearLayout) findViewById(R.id.ll_step);
        mStepDescTv = (TextView) findViewById(R.id.tv_step_desc);
        mRouteStepLv = (ListView) findViewById(R.id.lv_node_step);
        mStepLayout.setVisibility(View.GONE);
        mRouteIb = (ImageButton) findViewById(R.id.ib_route);
        mStepBackIv = (ImageView) findViewById(R.id.iv_step_back);
        mStepBackIv.setVisibility(View.GONE);
        mWXLayerLl = (LinearLayout) findViewById(R.id.ll_layer_wx);
        m2DLayerLl = (LinearLayout) findViewById(R.id.ll_layer_2d);
        m3DLayerLl = (LinearLayout) findViewById(R.id.ll_layer_3d);
        mPersonalMapCb = (CheckBox) findViewById(R.id.cb_personal_map);
        mRealRouteCb = (CheckBox) findViewById(R.id.cb_real_route);
        mHotMapCb = (CheckBox) findViewById(R.id.cb_hot_map);
        mModeCb = (CheckBox) findViewById(R.id.cb_mode);
        mModeLayout = (FrameLayout) findViewById(R.id.fl_mode_layout);
        mNoModeIv = (ImageView) findViewById(R.id.iv_no_mode);
        mNoModeIv.setVisibility(View.VISIBLE);
        mModeCb.setVisibility(View.GONE);
        setMapBottomMargin(0);

    }

    private void setMapBottomMargin(int value) {
        if (value == 0) {
            mRouteIb.setVisibility(View.VISIBLE);
            mTitleBarLl.setVisibility(View.VISIBLE);
            mModeLayout.setVisibility(View.VISIBLE);
            mBaiduMap.clear();
            //隐藏节点详情
            mStepLayout.setVisibility(View.GONE);
            mStepBackIv.setVisibility(View.GONE);
        } else {
            mTitleBarLl.setVisibility(View.GONE);
            mRouteIb.setVisibility(View.GONE);
            mModeLayout.setVisibility(View.GONE);
            mStepLayout.setVisibility(View.VISIBLE);
            mStepBackIv.setVisibility(View.VISIBLE);
        }
        mBaiduMap.setViewPadding(0, 0, 0, value);
    }

    /**
     * 获取定位信息
     */
    private void requestLocation() {
        mBaiduMap.setMyLocationEnabled(true);//启用我的位置
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(1000);//设置刷新间隔
        option.setCoorType("bd09ll"); // 设置坐标类型为百度坐标系统
        option.setIsNeedAddress(true);//需要获取当前位置的详细地址
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//高精度模式(gps/wifi/蓝牙/网络方式定位)
        mLocationClient.setLocOption(option);
        mLocationClient.start();

        // 初始化地理编码功能
        mGeoCoder = GeoCoder.newInstance();
        // 初始化搜索模块,注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();

    }

    private boolean isOpenSetpLayout;

    private void initListener() {
        // 地图点击事件处理
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();//清除地图弹出物
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        //点击marker弹出显示位置
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LatLng ll = marker.getPosition();
                if (null != mBusLineResult) {
                    //显示公交站poi
                    for (RouteNode routeNode : mBusLineResult.getStations()) {
                        if (routeNode.getLocation() == ll) {
                            showInfoWindow(routeNode.getTitle(), ll);
                            return true;
                        }
                    }
                } else if (-1 != nowSearchType) {
                    //通过反编码查询路线规划点击poi
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(ll));
                    mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
                }
                return true;
            }
        });
        //触摸地图
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                mNoModeIv.setVisibility(View.VISIBLE);
                mModeCb.setVisibility(View.GONE);
                isOpenLocation = false;
            }
        });
        //地理编码解析与反解析
        mGeoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result != null && result.error == SearchResult.ERRORNO.NO_ERROR) {
                    showInfoWindow(result.getAddress(), result.getLocation());
                }

            }
        });
        //主要用到详情搜索
        mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult result) {
                if (result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(BDMapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
                } else {
                    //显示搜索到的poi详情
                    showInfoWindow(result.getName() + " " + result.getAddress(), result.getLocation());
                }
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });

        //点击当前位置切换为跟随模式
        mNoModeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNoModeIv.setVisibility(View.GONE);
                mModeCb.setVisibility(View.VISIBLE);
                isOpenLocation = true;
                mModeCb.setChecked(false);
                mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
                m2DLayerLl.performClick();
            }
        });
        mStepBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "#BDMapActivity-mStepBackIv->startCityName:" + startCityName + " startPlaceName:" + startPlaceName +" mStartLatLng:"+mStartLatLng+" mEndLatLng:"+mEndLatLng);

                mBaiduMap.clear();//清除路况
                //返回路线选择页
                Intent intent = new Intent(BDMapActivity.this, RoutePlanActiviy.class);
                intent.putExtra("startLatlng", mStartLatLng);
                intent.putParcelableArrayListExtra("routeLineList", mCurrRouteLineList);
                intent.putExtra("endLatlng", mEndLatLng);
                intent.putExtra("cityName", startCityName);
                intent.putExtra("nowSearchType", nowSearchType);
                intent.putExtra("isAutoSearch", true);
                intent.putExtra("startNodeName", mStartNodeName);
                intent.putExtra("endNodeName", mEndNodeName);
                startActivityForResult(intent, REQ_SEARCH_ROUTE, null);
                setMapBottomMargin(0);
            }
        });
        mContentFl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContentFl.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mContentHeight = mContentFl.getHeight();
                FrameLayout.LayoutParams flp = (FrameLayout.LayoutParams) mStepLayout.getLayoutParams();
                flp.gravity = Gravity.BOTTOM;
                flp.height = mContentHeight * 1 / 4;
                mStepLayout.setLayoutParams(flp);
            }
        });
        //跳到路线规划图
        mRouteIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaiduMap.clear();
                Intent intent = new Intent(BDMapActivity.this, RoutePlanActiviy.class);
                intent.putExtra("startLatlng", mStartLatLng);
                intent.putExtra("endLatlng", mStartLatLng);
                intent.putExtra("cityName", startCityName);
                intent.putExtra("nowSearchType", nowSearchType);
                intent.putExtra("isAutoSearch", false);
                startActivityForResult(intent, REQ_SEARCH_ROUTE, null);
            }
        });
        mStepLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FrameLayout.LayoutParams flp = (FrameLayout.LayoutParams) mStepLayout.getLayoutParams();
                flp.gravity = Gravity.BOTTOM;
                if (!isOpenSetpLayout) {
                    isOpenSetpLayout = !isOpenSetpLayout;
                    flp.height = mContentHeight * 1 / 2;//打开

                } else {
                    isOpenSetpLayout = !isOpenSetpLayout;
                    flp.height = mContentHeight * 1 / 4;//关闭
                }
                mStepDescTv.setSelected(isOpenSetpLayout);//打开:右边箭头向下,关闭:右边箭头向上
                mStepLayout.setLayoutParams(flp);
                setMapBottomMargin(flp.height);

            }
        });
        mBackIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSettingIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(GravityCompat.END);
            }
        });
        mBusSearchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaiduMap.clear();
                Intent intent = new Intent(BDMapActivity.this, PoiSearchActivity.class);
                startActivityForResult(intent, REQ_SEARCH_BUSLINE, null);
            }
        });
        mWXLayerLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawers();
                //卫星地图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                saveLayerPosition(1);
            }
        });
        m2DLayerLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawers();
                //2D平面图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                MapStatus ms = new MapStatus.Builder(mBaiduMap.getMapStatus()).overlook(0).build();
                MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
                mBaiduMap.animateMapStatus(u);
                saveLayerPosition(2);
            }
        });
        m3DLayerLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawers();
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                MapStatus ms = new MapStatus.Builder(mBaiduMap.getMapStatus()).overlook(-45).build();
                MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
                mBaiduMap.animateMapStatus(u);
                saveLayerPosition(3);

            }
        });
        mPersonalMapCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mDrawerLayout.closeDrawers();
                MapView.setMapCustomEnable(isChecked);
                saveMapSetting("isPersonal", isChecked);
            }
        });
        mRealRouteCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mDrawerLayout.closeDrawers();
                mBaiduMap.setTrafficEnabled(isChecked);
                saveMapSetting("isRealRoute", isChecked);
            }
        });
        mHotMapCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mDrawerLayout.closeDrawers();
                mBaiduMap.setBaiduHeatMapEnabled(isChecked);
                saveMapSetting("isHotMap", isChecked);
            }
        });
        //跟随/罗盘模式切换
        mModeCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isOpenLocation = true;
                MyLocationConfiguration.LocationMode mode = isChecked ? MyLocationConfiguration.LocationMode.COMPASS : MyLocationConfiguration.LocationMode.FOLLOWING;
                mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mode, true, null));
                if (!isChecked) {
                    m2DLayerLl.performClick();
                }
            }
        });
    }

    private void saveLayerPosition(int position) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(BDMapActivity.this).edit();
        editor.putInt("layerPosition", position);
        editor.apply();
    }

    private void saveMapSetting(String key, boolean value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(BDMapActivity.this).edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    private void setLayerByPosition() {
        int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("layerPosition", 2);
        switch (position) {
            case 1://卫星图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                break;
            case 2://2d平面图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                MapStatus ms = new MapStatus.Builder(mBaiduMap.getMapStatus()).overlook(0).build();
                MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
                mBaiduMap.animateMapStatus(u);
                break;
            case 3://3d俯视图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                MapStatus mss = new MapStatus.Builder(mBaiduMap.getMapStatus()).overlook(-45).build();
                MapStatusUpdate uu = MapStatusUpdateFactory.newMapStatus(mss);
                mBaiduMap.animateMapStatus(uu);
                break;
        }
    }

    private void setMapSettingByLastSave() {
        boolean isPersonal = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isPersonal", false);
        boolean isRealRoute = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isRealRoute", false);
        boolean isHotMap = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isHotMap", false);
        mPersonalMapCb.setChecked(isPersonal);
        mRealRouteCb.setChecked(isRealRoute);
        mHotMapCb.setChecked(isHotMap);
    }

    /**
     * 更新位置时调用
     *
     * @param location
     */
    private void navigateTo(BDLocation location) {
        if (!isFirstLoc) {
            //首次进来定位
            isFirstLoc = true;
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            mStartLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            startCityName = location.getCity();
        }
        if (isOpenLocation) {
            //实时跟随定位
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息,顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
        }
        Log.d(TAG, isOpenLocation ? "开启自动定位" : "关闭自动定位");

//        startPlaceName = location.getDistrict() + location.getStreet();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            Log.d(TAG, "onReceiveLocation:" + bdLocation.getProvince() + "-" + bdLocation.getCity() + "-" + bdLocation.getDistrict());
            // map view 销毁后不在处理新接收的位置
            if (bdLocation == null || mMapView == null) {
                return;
            }
            if (!TextUtils.isEmpty(bdLocation.getProvince()) &&
                    !TextUtils.isEmpty(bdLocation.getCity()) &&
                    !TextUtils.isEmpty(bdLocation.getDistrict())) {
                navigateTo(bdLocation);
            }
        }
    }

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

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        MapView.setMapCustomEnable(false);
        // 退出时销毁定位
        mLocationClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            if (REQ_SEARCH_ROUTE == requestCode) {
                int linePosition = data.getIntExtra("linePosition", 1);
                boolean isSameCity = data.getBooleanExtra("isSameCity", false);//是否是同城,跨域交通用到
                RouteLine routeLine = data.getParcelableExtra("routeLine");
                mCurrRouteLineList = data.getParcelableArrayListExtra("routeLineList");
                nowSearchType = data.getIntExtra("nowSearchType", -1);
                mStartLatLng = data.getParcelableExtra("startLatlng");
                mEndLatLng = data.getParcelableExtra("endLatlng");
                startCityName = data.getStringExtra("startCityName");
                mStartNodeName = data.getStringExtra("startNodeName");
                mEndNodeName = data.getStringExtra("endNodeName");
                Log.d(TAG, "#BDMapActivity-onActivityResult->startCityName:" + startCityName + " startPlaceName:" + startPlaceName +" mStartLatLng:"+mStartLatLng+" mEndLatLng:"+mEndLatLng);

                if (null == routeLine || -1 == nowSearchType) {
                    Toast.makeText(BDMapActivity.this, "获取路线失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (nowSearchType) {
                    case RouteType.MASS_TRANSIT_ROUTE://跨城交通
                        MassTransitRouteOverlay overlay0 = new MassTransitRouteOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay0);
                        MassTransitRouteLine nowRouteMass = (MassTransitRouteLine) routeLine;
                        overlay0.setData(nowRouteMass);
                        if (isSameCity) {
                            overlay0.setSameCity(true); // 同城
                        } else {
                            overlay0.setSameCity(false);// 跨城
                        }
                        overlay0.addToMap();
                        overlay0.zoomToSpan();
                        break;
                    case RouteType.DRIVING_ROUTE://驾车
                        DrivingRouteOverlay overlay1 = new DrivingRouteOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay1);
                        DrivingRouteLine nowRouteDriving = (DrivingRouteLine) routeLine;
                        overlay1.setData(nowRouteDriving);
                        overlay1.addToMap();
                        overlay1.zoomToSpan();
                        break;
                    case RouteType.TRANSIT_ROUTE://公交
                        TransitRouteOverlay overlay2 = new TransitRouteOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay2);
                        TransitRouteLine nowRouteTransit = (TransitRouteLine) routeLine;
                        overlay2.setData(nowRouteTransit);
                        overlay2.addToMap();
                        overlay2.zoomToSpan();
                        break;
                    case RouteType.WALKING_ROUTE://步行
                        WalkingRouteOverlay overlay3 = new WalkingRouteOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay3);
                        WalkingRouteLine nowRouteWalking = (WalkingRouteLine) routeLine;
                        overlay3.setData(nowRouteWalking);
                        overlay3.addToMap();
                        overlay3.zoomToSpan();
                        break;
                    case RouteType.BIKING_ROUTE://骑行
                        BikingRouteOverlay overlay4 = new BikingRouteOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay4);
                        BikingRouteLine nowRouteBiking = (BikingRouteLine) routeLine;
                        overlay4.setData(nowRouteBiking);
                        overlay4.addToMap();
                        overlay4.zoomToSpan();
                        break;
                }
                showRouteDesc(nowSearchType, routeLine, linePosition, isSameCity);

            } else if (requestCode == REQ_SEARCH_BUSLINE) {
                int type = data.getIntExtra("type", 0);
                if (type == PoiSearchActivity.TYPE_BUS_LINE) {
                    mBusLineResult = data.getParcelableExtra("busLineResult");
                    BusLineOverlay overlay = new BusLineOverlay(mBaiduMap);
                    mBaiduMap.setOnMarkerClickListener(overlay);
                    overlay.setData(mBusLineResult);
                    overlay.addToMap();
                    overlay.zoomToSpan();
                } else if (type == PoiSearchActivity.TYPE_HAVE_FUN) {
                    PoiResult result = data.getParcelableExtra("poiResult");
                    mBaiduMap.clear();
                    PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
                    mBaiduMap.setOnMarkerClickListener(overlay);
                    overlay.setData(result);
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }

            }
        }
    }

    /**
     * 显示线路描述
     *
     * @param nowSearchType
     * @param routeLine
     * @param linePosition
     * @param isSameCity
     */
    private void showRouteDesc(int nowSearchType, RouteLine routeLine, int linePosition, boolean isSameCity) {
        StringBuilder desc = new StringBuilder();
        switch (nowSearchType) {
            case RouteType.TRANSIT_ROUTE:
            case RouteType.WALKING_ROUTE:
            case RouteType.BIKING_ROUTE:
                desc.append("路线" + linePosition);
                int time = routeLine.getDuration();
                if (time / 3600 == 0) {
                    desc.append(" 大约需要:" + time / 60 + "分钟");
                } else {
                    desc.append(" 大约需要:" + time / 3600 + "小时" + (time % 3600) / 60 + "分钟");
                }
                desc.append(" 距离大约是:" + routeLine.getDistance() + "米");
                break;
            case RouteType.DRIVING_ROUTE:
                desc.append("路线" + linePosition);
                DrivingRouteLine drivingRouteLine = (DrivingRouteLine) routeLine;
                desc.append(" 红绿灯数:" + drivingRouteLine.getLightNum());
                desc.append(" 拥堵距离为:" + drivingRouteLine.getCongestionDistance() + "米");
                break;
            case RouteType.MASS_TRANSIT_ROUTE:
                MassTransitRouteLine massTransitRouteLine = (MassTransitRouteLine) routeLine;
                desc.append("路线" + linePosition);
                desc.append(" 预计达到时间:" + massTransitRouteLine.getArriveTime());
                desc.append(" 总票价:" + massTransitRouteLine.getPrice() + "元");
                break;
        }
        mStepDescTv.setText(desc.toString());
        List<RouteStep> steps = null;
        if (nowSearchType == 0) {
            MassTransitRouteLine massroute = (MassTransitRouteLine) routeLine;
            int size = 0;
            if (isSameCity) {
                size = massroute.getNewSteps().size();
            } else {
                for (int i = 0; i < massroute.getNewSteps().size(); i++) {
                    size += massroute.getNewSteps().get(i).size();
                }
            }
            steps = new ArrayList<>();
            for (int nodeIndex = 0; nodeIndex < size; nodeIndex++) {
                if (isSameCity) {
                    // 同城
                    steps.add(massroute.getNewSteps().get(nodeIndex).get(0));
                } else {
                    // 跨城
                    int num = 0;
                    for (int j = 0; j < massroute.getNewSteps().size(); j++) {
                        num += massroute.getNewSteps().get(j).size();
                        if (nodeIndex - num < 0) {
                            int k = massroute.getNewSteps().get(j).size() + nodeIndex - num;
                            steps.add(massroute.getNewSteps().get(j).get(k));
                            break;
                        }
                    }
                }
            }
        } else {
            steps = routeLine.getAllStep();
        }
        if (null != steps && steps.size() > 0) {
            //显示路线详情
            setMapBottomMargin(mContentHeight * 1 / 4);
            RouteStepAdapter stepAdapter = new RouteStepAdapter(this, steps);
            mRouteStepLv.setAdapter(stepAdapter);
        }
        mRouteStepLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RouteStep step = (RouteStep) parent.getItemAtPosition(position);
                LatLng nodeLocation = null;
                if (step instanceof DrivingRouteLine.DrivingStep) {
                    DrivingRouteLine.DrivingStep drivingStep = (DrivingRouteLine.DrivingStep) step;
                    nodeLocation = drivingStep.getEntrance().getLocation();
                } else if (step instanceof WalkingRouteLine.WalkingStep) {
                    WalkingRouteLine.WalkingStep walkingStep = (WalkingRouteLine.WalkingStep) step;
                    nodeLocation = walkingStep.getEntrance().getLocation();
                } else if (step instanceof TransitRouteLine.TransitStep) {
                    TransitRouteLine.TransitStep transitStep = (TransitRouteLine.TransitStep) step;
                    nodeLocation = transitStep.getEntrance().getLocation();

                } else if (step instanceof BikingRouteLine.BikingStep) {
                    BikingRouteLine.BikingStep bikingStep = (BikingRouteLine.BikingStep) step;
                    nodeLocation = bikingStep.getEntrance().getLocation();

                } else if (step instanceof MassTransitRouteLine.TransitStep) {
                    MassTransitRouteLine.TransitStep massStep = (MassTransitRouteLine.TransitStep) step;
                    nodeLocation = massStep.getStartLocation();

                }
                // 移动节点至中心
                if (null != nodeLocation) {
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
                    //查询当前选中位置
                    mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(nodeLocation));
                }
            }
        });
    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(poi.uid));
            return true;
        }
    }

    // show popup
    private void showInfoWindow(String txt, LatLng latLng) {
        TextView popupText = new TextView(BDMapActivity.this);
        popupText.setPadding(5, 5, 5, 30);
        popupText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        popupText.setBackgroundResource(R.drawable.popup);
        popupText.setTextColor(0xFF000000);
        popupText.setText(txt);
        mBaiduMap.showInfoWindow(new InfoWindow(popupText, latLng, 0));
    }

    @Override
    public void onBackPressed() {
        if (mStepLayout.isShown()) {
            setMapBottomMargin(0);
            return;
        }
        super.onBackPressed();
    }

    // 设置个性化地图config文件路径
    private void setMapCustomFile(Context context) {
        FileOutputStream out = null;
        InputStream inputStream = null;
        String moduleName = null;
        try {
            inputStream = context.getAssets().open("customConfigdir/custom_config.txt");
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);

            moduleName = context.getFilesDir().getAbsolutePath();
            File f = new File(moduleName + "/" + "custom_config.txt");
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
            out = new FileOutputStream(f);
            out.write(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        MapView.setCustomMapStylePath(moduleName + "/custom_config.txt");
    }
}


text:
[![build status](https://img.shields.io/travis/glennjones/microformat-node.svg?style=flat-square)](http://travis-ci.org/glennjones/microformat-node)
[![Coverage Status](https://img.shields.io/coveralls/glennjones/microformat-node/master.svg?style=flat-square)](https://coveralls.io/r/glennjones/microformat-node)
[![Codacy Badge](https://img.shields.io/codacy/grade/20b227b0a05642a2bbc6cecdf07f1387.svg?style=flat-square)](https://www.codacy.com/app/glennjonesnet/microformat-node)
[![MIT license](http://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://raw.github.com/glennjones/microformat-shic/master/license.txt)

microformat-node
================
A node.js microformats parser. It is the same codebase as  [microformat-shiv](https://github.com/glennjones/microformat-shiv) project, but
used the ultra-fast HTML DOM [cheerio]( https://github.com/cheeriojs/cheerio) to parse HTML. The microformat-shiv library is also used in Firefox browser
as an internal component.

Installation
------------

Using bower:

```sh
$ npm install microformat-node
```

Methods
-----
* Parsing
    * [`get`](#get)
* Discovery
    * [`count`](#count)
    * [`isMicroformat`](#isMicroformat)
    * [`hasMicroformats`](#hasMicroformats)

get
-----
The `get` method parses microformats data from either a `html` string or a `cheerio` object.

Simple parse of HTML string.
```javascript
    var Microformats = require('microformat-node'),
        options = {};

    options.html = '<a class="h-card" href="http://glennjones.net">Glenn</a>';
    Microformats.get(options, function(err, data){
        // do something with data
    });
```

Simple parse of a Cheerio parsed page
```javascript
    var Microformats = require('microformat-node'),
        Cheerio = require('cheerio'),
        options = {};

    options.node = Cheerio.load('<a class="h-card" href="http://glennjones.net">Glenn</a>');
    Microformats.get(options, function(err, data){
        // do something with data
    });
```

Options
-------
* `html` - (String) the html to be parse
* `node` - (Cheerio DOM object) the element to be parse
* `filter` - (Array) microformats types returned - i.e. `['h-card']` - always adds `rels`
* `baseUrl` - (String) a base URL to resolve any relative URL:s to
* `textFormat` - (String) text style `whitespacetrimmed` or `normalised` default is `whitespacetrimmed`
* `dateFormat` - (String) the ISO date profile `auto`, `microformat2`, `w3c` `rfc3339` or `html5` default is `auto`
* `add` - (Array) adds microformat version 1 definitions

__I would recommended always setting `textFormat` option to `normalised`. This is not part of the microformat parsing rules, but in most cases provides more usable output.__

Experimental Options
-------
These options are part of ongoing specification development. They maybe removed or renamed in future.
* `lang` (Boolean) Parses and adds the language value to e-* default is false
* `parseLatLonGeo` (Boolean)  Parse geo date writen as latlon i.e. 30.267991;-97.739568
default is `false`

Output
-------
JSON output. This is an example of a parsed `h-card` microformat.
```javascript
    {
        "items": [{
            "type": ["h-card"],
             "properties": {
                "url": ["http://blog.lizardwrangler.com/"],
                "name": ["Mitchell Baker"],
                "org": ["Mozilla Foundation"],
                "note": ["Mitchell is responsible for setting the direction Mozilla ..."],
                "category": ["Strategy", "Leadership"]
             }
        }],
        "rels": {},
        "rel-urls": {}
    }
```
Count
-----
The `count` method returns the number of each microformat type found. It does not do a full parse so it is much quicker
than get and can be used for tasks such as adding notifications to the UI. The method can take a `options` object as a parameter.
```javascript
    var Microformats = require('microformat-node'),
        options = {};

    options.html = '<a class="h-card" href="http://glennjones.net">Glenn</a>';
    Microformats.count(options, function(err, data){
        // do something with data
    });
```
Output
```javascript
    {
        'h-event': 1,
        'h-card': 2,
        'rels': 6
    }
```

isMicroformat
-------------
The `isMicroformat` method returns weather a node has a valid microformats class. It currently does not work consider
`rel=*` a microformats. The method can take a `options` object as a second parameter.
```javascript
    var Microformats = require('microformat-node'),
        options = {};

    options.html = '<a class="h-card" href="http://glennjones.net">Glenn</a>';
    Microformats.isMicroformat(options, function(err, isValid){
        // do something with isValid
    });
```

hasMicroformats
-------------
The `hasMicroformats` method returns weather a document or node has any valid microformats class. It currently does
not take rel=* microformats into account. The method can take a `options` object as a second parameter.
```javascript
    var Microformats = require('microformat-node'),
        options = {};

    options.html = '<div><a class="h-card" href="http://glennjones.net">Glenn</a></div>';
    Microformats.hasMicroformats(options, function(err, isValid){
        // do something with isValid
    });
```

using a promise
-------------
There are promise based version of the four public methods, each is appended with the text `Async`. So the names for promise methods are `getAsync`, `countAsync`, `isMicroformatAsync` and `hasMicroformatsAsync`.

```javascript
    var Microformats = require('microformat-node'),
        options = {};

    options.html = '<a class="h-card" href="http://glennjones.net">Glenn</a>';
    Microformats.getAsync(options)
        .then(function (data) {
            // do something with data
        })
        .catch(function(err){
            // do something with err
        })
```
Version and livingStandard
--------------------------
The library has two properties to help identify now up todate it is:

*  `version` (String) interanl version number
*  `livingStandard` (String ISO Date) the current https://github.com/microformats/tests used.

Microformats definitions object
-------------------------------
The library has built-in version 1 microformats definitions, but you can add new definitions using `options.add` if you wish. Below is an example of a definitions object. Examples of existing definitions found in the directory `lib/maps`. You not need to add new definitions object if your using the microformats version 2.
```javascript
    {
		root: 'hpayment',
		name: 'h-payment',
		properties: {
			'amount': {},
			'currency': {}
		}
	}
```

Running simple demo page
-------------------------------

```sh
$ git clone https://github.com/glennjones/microformat-node.git
$ cd microformat-node
$ npm i
$ npm start
```
Then open http://0.0.0.0:3000

License
-------

[MIT][] © Copyright [Glenn Jones][]

[MIT]: ./License.md
[Glenn Jones]: https://github.com/glennjones

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shardingsphere.sql.parser.sql.statement.tcl;

import org.apache.shardingsphere.sql.parser.sql.statement.AbstractSQLStatement;

/**
 * Transaction Control Language statement.
 */
public abstract class TCLStatement extends AbstractSQLStatement {
}


text:
package org.frameworkset.http.converter;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletResponse;

import org.frameworkset.http.HttpHeaders;
import org.frameworkset.http.HttpInputMessage;
import org.frameworkset.http.HttpOutputMessage;
import org.frameworkset.http.MediaType;
import org.frameworkset.http.StreamingHttpOutputMessage;
import org.frameworkset.http.converter.AbstractHttpMessageConverter;
import org.frameworkset.http.converter.HttpMessageNotWritableException;

public abstract class AbstractGenericHttpMessageConverter<T> extends AbstractHttpMessageConverter<T>
		implements GenericHttpMessageConverter<T> {

	/**
	 * Construct an {@code AbstractGenericHttpMessageConverter} with no
	 * supported media types.
	 *
	 * @see #setSupportedMediaTypes
	 */
	protected AbstractGenericHttpMessageConverter() {
	}

	/**
	 * Construct an {@code AbstractGenericHttpMessageConverter} with one
	 * supported media type.
	 *
	 * @param supportedMediaType
	 *            the supported media type
	 */
	protected AbstractGenericHttpMessageConverter(MediaType supportedMediaType) {
		super(supportedMediaType);
	}

	/**
	 * Construct an {@code AbstractGenericHttpMessageConverter} with multiple
	 * supported media type.
	 *
	 * @param supportedMediaTypes
	 *            the supported media types
	 */
	protected AbstractGenericHttpMessageConverter(MediaType... supportedMediaTypes) {
		super(supportedMediaTypes);
	}

	@Override
	public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
		return canRead(contextClass, mediaType);
	}

	@Override
	public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) {
		return canWrite(clazz, mediaType);
	}

	/**
	 * This implementation sets the default headers by calling {@link #addDefaultHeaders},
	 * and then calls {@link #writeInternal}.
	 */
	public final void write(final T t, final Type type, MediaType contentType, final HttpOutputMessage outputMessage,final HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotWritableException {

		final HttpHeaders headers = outputMessage.getHeaders();
		addDefaultHeaders(headers, t, contentType);

		if (outputMessage instanceof StreamingHttpOutputMessage) {
			StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
			streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
				@Override
				public void writeTo(final OutputStream outputStream) throws IOException {
					writeInternal(t, type, new HttpOutputMessage() {
						@Override
						public OutputStream getBody() throws IOException {
							return outputStream;
						}
						@Override
						public HttpHeaders getHeaders() {
							return headers;
						}
						@Override
						public HttpServletResponse getResponse() {
							// TODO Auto-generated method stub
							return outputMessage.getResponse();
						}
					},inputMessage);
				}
			});
		}
		else {
			writeInternal(t, type, outputMessage,inputMessage);
			outputMessage.getBody().flush();
		}
	}

	@Override
	public void writeInternal(T t,  HttpOutputMessage outputMessage,HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotWritableException {

		writeInternal(t, null, outputMessage,inputMessage);
	}

	/**
	 * Abstract template method that writes the actual body. Invoked from
	 * {@link #write}.
	 *
	 * @param t
	 *            the object to write to the output message
	 * @param type
	 *            the type of object to write, can be {@code null} if not
	 *            specified.
	 * @param outputMessage
	 *            the HTTP output message to write to
	 * @throws IOException
	 *             in case of I/O errors
	 * @throws HttpMessageNotWritableException
	 *             in case of conversion errors
	 */
	protected abstract void writeInternal(T t, Type type, HttpOutputMessage outputMessage,HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotWritableException;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="2.5" client="administrator">
	<name>mod_version</name>
	<creationDate>January 2015</creationDate>
	<author>HUBzero</author>
	<authorUrl>hubzero.org</authorUrl>
	<authorEmail>support@hubzero.org</authorEmail>
	<copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright>
	<license>http://opensource.org/licenses/MIT MIT</license>
	<version>1.0.0</version>
	<description>MOD_VERSION_XML_DESCRIPTION</description>
	<files>
		<filename module="mod_version">mod_version.php</filename>
		<filename>helper.php</filename>
		<filename>index.html</filename>
		<folder>tmpl</folder>
		<folder>language</folder>
	</files>
	<languages>
		<language tag="en-GB">language/en-GB/en-GB.mod_version.ini</language>
		<language tag="en-GB">language/en-GB/en-GB.mod_version.sys.ini</language>
	</languages>
	<help key="JHELP_EXTENSIONS_MODULE_MANAGER_ADMIN_VERSION" />
	<config>
		<fields name="params">
			<fieldset name="basic">
				<field name="format" type="list" default="short" label="MOD_VERSION_FORMAT_LABEL" description="MOD_VERSION_FORMAT_DESC">
					<option value="short">MOD_VERSION_FORMAT_SHORT</option>
					<option value="long">MOD_VERSION_FORMAT_LONG</option>
				</field>
				<field name="product" type="list" default="1" label="MOD_VERSION_PRODUCT_LABEL" description="MOD_VERSION_PRODUCT_DESC">
					<option value="1">JYES</option>
					<option value="0">JNO</option>
				</field>
			</fieldset>
			<fieldset name="advanced">
				<field name="layout" type="modulelayout" label="JFIELD_ALT_LAYOUT_LABEL" description="JFIELD_ALT_MODULE_LAYOUT_DESC" />
				<field name="moduleclass_sfx" type="text" label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL" description="COM_MODULES_FIELD_MODULECLASS_SFX_DESC" />
				<field name="cache" type="list" default="0" label="COM_MODULES_FIELD_CACHING_LABEL" description="COM_MODULES_FIELD_CACHING_DESC">
					<option value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>


text:
namespace py = pybind11;

gem5Component::gem5Component(SST::ComponentId_t id, SST::Params& params):
    SST::Component(id), threadInitialized(false)
{
    output.init("gem5Component-" + getName() + "->", 1, 0,
                SST::Output::STDOUT);

    std::string cpu_frequency = params.find<std::string>("frequency", "");
    if (cpu_frequency.empty()) {
        output.fatal(
            CALL_INFO, -1, "The frequency of the CPU must be specified.\n"
        );
    }

    // Register a handler to be called on a set frequency.
    timeConverter = registerClock(
        cpu_frequency,
        new SST::Clock::Handler<gem5Component>(this, &gem5Component::clockTick)
    );

    // "cmd" -> gem5's Python
    std::string cmd = params.find<std::string>("cmd", "");
    if (cmd.empty()) {
        output.fatal(
            CALL_INFO, -1, "Component %s must have a 'cmd' parameter.\n",
            getName().c_str()
        );
    }

    // Telling SST the command line call to gem5
    args.push_back(const_cast<char*>("sst.x"));
    splitCommandArgs(cmd, args);
    output.output(CALL_INFO, "Command string:  [sst.x %s]\n", cmd.c_str());
    for (size_t i = 0; i < args.size(); ++i) {
        output.output(CALL_INFO, "  Arg [%02zu] = %s\n", i, args[i]);
    }

    // Parsing and setting gem5 debug flags
    std::string gem5_debug_flags = params.find<std::string>("debug_flags", "");
    for (auto const debug_flag: tokenizeString(gem5_debug_flags, {' ', ','})) {
        output.output(CALL_INFO, "Debug flag += %s\n", debug_flag.c_str());
        gem5::setDebugFlag(debug_flag.c_str());
    }

    registerAsPrimaryComponent();
    primaryComponentDoNotEndSim();

    systemPort = \
        loadUserSubComponent<SSTResponderSubComponent>("system_port",0);
    cachePort = \
        loadUserSubComponent<SSTResponderSubComponent>("cache_port", 0);

    systemPort->setTimeConverter(timeConverter);
    systemPort->setOutputStream(&(output));
    cachePort->setTimeConverter(timeConverter);
    cachePort->setOutputStream(&(output));

}

gem5Component::~gem5Component()
{
}

void
gem5Component::init(unsigned phase)
{
    output.output(CALL_INFO," init phase: %u\n", phase);

    if (phase == 0) {
        initPython(args.size(), &args[0]);

        const std::vector<std::string> m5_instantiate_commands = {
            "import m5",
            "m5.instantiate()"
        };
        execPythonCommands(m5_instantiate_commands);

        // calling SimObject.startup()
        const std::vector<std::string> simobject_setup_commands = {
            "import atexit",
            "import _m5.core",
            "import m5",
            "import m5.stats",
            "import m5.objects.Root",
            "root = m5.objects.Root.getInstance()",
            "for obj in root.descendants(): obj.startup()",
            "atexit.register(m5.stats.dump)",
            "atexit.register(_m5.core.doExitCleanup)",
            "m5.stats.reset()"
        };
        execPythonCommands(simobject_setup_commands);

        // find the corresponding SimObject for each SSTResponderSubComponent
        gem5::Root* gem5_root = gem5::Root::root();
        systemPort->findCorrespondingSimObject(gem5_root);
        cachePort->findCorrespondingSimObject(gem5_root);

        // initialize the gem5 event queue
        if (!(threadInitialized)) {
            threadInitialized = true;
            gem5::simulate_limit_event = new gem5::GlobalSimLoopExitEvent(
                gem5::mainEventQueue[0]->getCurTick(),
                "simulate() limit reached",
                0
            );
        }

    }

    systemPort->init(phase);
    cachePort->init(phase);
}

void
gem5Component::setup()
{
    output.verbose(CALL_INFO, 1, 0, "Component is being setup.\n");
    systemPort->setup();
    cachePort->setup();
}

void
gem5Component::finish()
{
    output.verbose(CALL_INFO, 1, 0, "Component is being finished.\n");
}

bool
gem5Component::clockTick(SST::Cycle_t currentCycle)
{
    // what to do in a SST's cycle
    gem5::GlobalSimLoopExitEvent *event = simulateGem5(currentCycle);
    clocksProcessed++;
    // gem5 exits due to reasons other than reaching simulation limit
    if (event != gem5::simulate_limit_event) {
        output.output("exiting: curTick()=%lu cause=`%s` code=%d\n",
            gem5::curTick(), event->getCause().c_str(), event->getCode()
        );
        // output gem5 stats
        const std::vector<std::string> output_stats_commands = {
            "import m5.stats",
            "m5.stats.dump()"
        };
        execPythonCommands(output_stats_commands);

        primaryComponentOKToEndSim();
        return true;
    }

    // returning False means the simulation should go on
    return false;

}

#define PyCC(x) (const_cast<char *>(x))

gem5::GlobalSimLoopExitEvent*
gem5Component::simulateGem5(uint64_t current_cycle)
{
    // This function should be similar to simulate() of src/sim/simulate.cc
    // with synchronization barriers removed.

    inform_once("Entering event queue @ %d.  Starting simulation...\n",
                gem5::curTick());

    // Tick conversion
    // The main logic for synchronize SST Tick and gem5 Tick is here.
    // next_end_tick = current_cycle * timeConverter->getFactor()
    uint64_t next_end_tick = \
        timeConverter->convertToCoreTime(current_cycle);

    // Here, if the next event in gem5's queue is not executed within the next
    // cycle, there's no need to enter the gem5's sim loop.
    if (gem5::mainEventQueue[0]->empty() ||
        next_end_tick < gem5::mainEventQueue[0]->getHead()->when()) {
        return gem5::simulate_limit_event;
    }
    gem5::simulate_limit_event->reschedule(next_end_tick);
    gem5::Event *local_event = doSimLoop(gem5::mainEventQueue[0]);
    gem5::BaseGlobalEvent *global_event = local_event->globalEvent();
    gem5::GlobalSimLoopExitEvent *global_exit_event =
        dynamic_cast<gem5::GlobalSimLoopExitEvent *>(global_event);
    return global_exit_event;
}

gem5::Event*
gem5Component::doSimLoop(gem5::EventQueue* eventq)
{
    // This function should be similar to doSimLoop() in src/sim/simulate.cc
    // with synchronization barriers removed.
    gem5::curEventQueue(eventq);
    eventq->handleAsyncInsertions();

    while (true)
    {
        // there should always be at least one event (the SimLoopExitEvent
        // we just scheduled) in the queue

        assert(!eventq->empty());
        assert(gem5::curTick() <= eventq->nextTick() &&
               "event scheduled in the past");

        if (gem5::async_event) {
            // Take the event queue lock in case any of the service
            // routines want to schedule new events.
            if (gem5::async_statdump || gem5::async_statreset) {
                gem5::statistics::schedStatEvent(gem5::async_statdump,
                                                 gem5::async_statreset);
                gem5::async_statdump = false;
                gem5::async_statreset = false;
            }

            if (gem5::async_io) {
                gem5::async_io = false;
                gem5::pollQueue.service();
            }

            if (gem5::async_exit) {
                gem5::async_exit = false;
                gem5::exitSimLoop("user interrupt received");
            }

            if (gem5::async_exception) {
                gem5::async_exception = false;
                return NULL;
            }
        }

        gem5::Event *exit_event = eventq->serviceOne();
        if (exit_event != NULL) {
            return exit_event;
        }
    }
}

int
gem5Component::execPythonCommands(const std::vector<std::string>& commands)
{
    static PyObject *dict =
        py::module_::import("__main__").attr("__dict__").ptr();

    PyObject *result;

    for (auto const command: commands) {
        result = PyRun_String(command.c_str(), Py_file_input, dict, dict);
        if (!result) {
            PyErr_Print();
            return 1;
        }
        Py_DECREF(result);
    }
    return 0;
}

void
gem5Component::initPython(int argc, char *_argv[])
{
    // Initialize gem5 special signal handling.
    gem5::initSignals();

    if (!Py_IsInitialized()) {
        py::initialize_interpreter(true, argc, _argv);
    } else {
        // pybind doesn't provide a way to set sys.argv if not initializing the
        // interpreter, so we have to do that manually if it's already running.
        py::list py_argv;
        auto sys = py::module::import("sys");
        if (py::hasattr(sys, "argv")) {
            // sys.argv already exists, so grab that.
            py_argv = sys.attr("argv");
        } else {
            // sys.argv doesn't exist, so create it.
            sys.add_object("argv", py_argv);
        }
        // Clear out argv just in case it has something in it.
        py_argv.attr("clear")();

        // Fill it with our argvs.
        for (int i = 0; i < argc; i++)
            py_argv.append(_argv[i]);
    }

    auto importer = py::module_::import("importer");
    importer.attr("install")();

    try {
        py::module_::import("m5").attr("main")();
    } catch (py::error_already_set &e) {
        if (!e.matches(PyExc_SystemExit)) {
            std::cerr << e.what();
            output.output(CALL_INFO, "Calling m5.main(...) failed.\n");
        }
    }
}

void
gem5Component::splitCommandArgs(std::string &cmd, std::vector<char*> &args)
{
    std::vector<std::string> parsed_args = tokenizeString(
        cmd, {'\\', ' ', '\'', '\"'}
    );

    for (auto part: parsed_args)
        args.push_back(strdup(part.c_str()));
}


text:
namespace net {

// A loss detection algorithm which avoids spurious losses and retransmissions
// by waiting 1.25 RTTs after a packet was sent instead of nack count.
class NET_EXPORT_PRIVATE TimeLossAlgorithm : public LossDetectionInterface {
 public:
  TimeLossAlgorithm();
  ~TimeLossAlgorithm() override {}

  LossDetectionType GetLossDetectionType() const override;

  // Declares pending packets less than the largest observed lost when it has
  // been 1.25 RTT since they were sent.  Packets larger than the largest
  // observed are retransmitted via TLP.
  SequenceNumberSet DetectLostPackets(
      const QuicUnackedPacketMap& unacked_packets,
      const QuicTime& time,
      QuicPacketSequenceNumber largest_observed,
      const RttStats& rtt_stats) override;

  // Returns the time the next packet will be lost, or zero if there
  // are no nacked pending packets outstanding.
  // TODO(ianswett): Ideally the RTT variance and the RTT would be used to
  // determine the time a packet is considered lost.
  // TODO(ianswett): Consider using Max(1.25 * srtt, 1.125 * last_rtt).
  QuicTime GetLossTimeout() const override;

 private:
  QuicTime loss_detection_timeout_;

  DISALLOW_COPY_AND_ASSIGN(TimeLossAlgorithm);
};

}  // namespace net

#endif  // NET_QUIC_CONGESTION_CONTROL_TIME_LOSS_ALGORITHM_H_


text:
package org.guvnor.ala.services.api.itemlist;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.guvnor.ala.runtime.providers.ProviderType;
import org.guvnor.ala.services.api.ItemList;

public class ProviderTypeList implements ItemList<ProviderType> {

    private ProviderType[] providerTypes;

    /*
     * No-args constructor for enabling marshalling to work, please do not remove.
    */
    public ProviderTypeList() {
    }

    public ProviderTypeList(List<ProviderType> providerTypes) {
        this.providerTypes = providerTypes.toArray(new ProviderType[providerTypes.size()]);
    }

    public ProviderTypeList(ProviderType[] providers) {
        this.providerTypes = providers;
    }

    public ProviderType[] getProviderTypes() {
        return providerTypes;
    }

    public void setProviderTypes(ProviderType[] pipelines) {
        this.providerTypes = pipelines;
    }

    @Override
    @JsonIgnore
    public List<ProviderType> getItems() {
        if (providerTypes == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(providerTypes);
    }
}


text:
#import "NotEnoughGoodsException.h"

@implementation NotEnoughGoodsException

- (id)initWithItemId:(NSString*)itemId{
    NSString* reason = [NSString stringWithFormat:@"You tried to equip virtual good with itemId: %@ but you don't have any of it." ,itemId];

    self = [super initWithName:@"InsufficientFundsException" reason:reason userInfo:nil];
    if (self){
    }

    return self;

}
@end


text:
@interface GPUImageGammaFilter : GPUImageFilter
{
    GLint gammaUniform;
}

// Gamma ranges from 0.0 to 3.0, with 1.0 as the normal level
@property(readwrite, nonatomic) CGFloat gamma;

@end


text:
#include <aws/privatenetworks/model/NetworkResourceType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace PrivateNetworks
  {
    namespace Model
    {
      namespace NetworkResourceTypeMapper
      {

        static const int RADIO_UNIT_HASH = HashingUtils::HashString("RADIO_UNIT");

        NetworkResourceType GetNetworkResourceTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == RADIO_UNIT_HASH)
          {
            return NetworkResourceType::RADIO_UNIT;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<NetworkResourceType>(hashCode);
          }

          return NetworkResourceType::NOT_SET;
        }

        Aws::String GetNameForNetworkResourceType(NetworkResourceType enumValue)
        {
          switch(enumValue)
          {
          case NetworkResourceType::RADIO_UNIT:
            return "RADIO_UNIT";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace NetworkResourceTypeMapper
    } // namespace Model
  } // namespace PrivateNetworks
} // namespace Aws


text:
from pymisp import PyMISP
from keys import misp_url, misp_key
import argparse

# For python2 & 3 compat, a bit dirty, but it seems to be the least bad one
try:
    input = raw_input
except NameError:
    pass

def init(url, key):
    return PyMISP(url, key, True, 'json')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Add sighting.')
    parser.add_argument("-f", "--json_file", required=True, help="The name of the json file describing the attribute you want to add sighting to.")
    args = parser.parse_args()

    misp = init(misp_url, misp_key)

    misp.sighting_per_json(args.json_file)


text:
if( NOT "${CTK_QT_VERSION}" MATCHES "4|5" )
  message( FATAL_ERROR "CTK_QT_VERSION should be set to either 4 or 5" )
endif()

set( CTK_SOURCE_DIR "/usr/src/CTK" )
set( CTK_BINARY_DIR "/usr/src/CTK-build" )

set( CTEST_SOURCE_DIRECTORY "${CTK_SOURCE_DIR}" )
set( CTEST_BINARY_DIRECTORY "${CTK_BINARY_DIR}/CTK-build" )

#############

set( SITE_CTEST_MODE "Experimental" ) # Experimental, Continuous, or Nightly

set( CTEST_CMAKE_GENERATOR "Unix Makefiles" ) # Ninja or Unix Makefiles

set( CTK_GIT_REPOSITORY "https://github.com/commontk/CTK.git" )

# Follow format for caps and components as given on CTK dashboard
set( CTEST_SITE "CircleCI_CTK" )

# Follow format for caps and components as given on CTK dashboard
set( SITE_PLATFORM "Ubuntu-64" )

# Use SITE_BUILD_TYPE specified by circle.yml
set( SITE_BUILD_TYPE "$ENV{SITE_BUILD_TYPE}" )
if( NOT( (SITE_BUILD_TYPE MATCHES "Debug") OR (SITE_BUILD_TYPE MATCHES "Release") ) )
  set( SITE_BUILD_TYPE "Debug" ) # Release, Debug
endif()

# Named SITE_BUILD_NAME
string( SUBSTRING $ENV{CIRCLE_SHA1} 0 7 commit )
set( what $ENV{CIRCLE_BRANCH} )
set( SITE_BUILD_NAME_SUFFIX _${commit}_${what} )

set( SITE_BUILD_NAME "CircleCI-${SITE_PLATFORM}-${SITE_BUILD_TYPE}${SITE_BUILD_NAME_SUFFIX}" )

set( CTEST_BUILD_NAME "${SITE_BUILD_NAME}-BuildTest-Qt${CTK_QT_VERSION}-${SITE_CTEST_MODE}" )

###################

set( CTEST_CONFIGURATION_TYPE "${SITE_BUILD_TYPE}")
set( CMAKE_BUILD_TYPE "${SITE_BUILD_TYPE}")
set( BUILD_TESTING ON )
set( CTK_BUILD_EXAMPLES OFF )

# Disable MIT_SHM X11 extension
set( ENV{QT_X11_NO_MITSHM} 1 )

###################

set(ctk_configure_options
  -DCTK_QT_VERSION:STRING=${CTK_QT_VERSION}
  -DCTK_ENABLE_Widgets:BOOL=ON
  )

ctest_start( "${SITE_CTEST_MODE}" )

ctest_configure(
  BUILD "${CTK_BINARY_DIR}"
  SOURCE "${CTK_SOURCE_DIR}"
  OPTIONS "${ctk_configure_options}"
  )

ctest_build( BUILD ${CTK_BINARY_DIR} )

ctest_test(
  BUILD ${CTEST_BINARY_DIRECTORY}
  RETURN_VALUE result
  )

ctest_submit()

if(result)
  message(FATAL_ERROR "ERROR: Tests failed")
endif()


text:
import '../styles/tailwind.css';

import { ComponentMeta, ComponentStory } from '@storybook/react';
import classNames from 'classnames';
import * as React from 'react';
import type { GroupBase, OptionProps, ValueContainerProps } from 'react-select';
import Select, { components } from 'react-select';
import { omit } from 'remeda';

import { Field } from '../components';
import type { PersonOption } from '../data';
import { defaultArgs, people } from '../data';

export default {
  title: 'Select/Tailwind',
  component: Select,
  argTypes: {},
} as ComponentMeta<typeof Select>;

function StatusCircle({ online }: { online?: boolean }) {
  return (

  );
}

function CheckIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 20 20"
      fill="currentColor"
      aria-hidden="true"
      {...props}
    >
      <path
        fillRule="evenodd"
        d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
        clipRule="evenodd"
      />
    </svg>
  );
}

function ValueContainer<
  IsMulti extends boolean = false,
  Group extends GroupBase<PersonOption> = GroupBase<PersonOption>
>({ children, ...props }: ValueContainerProps<PersonOption, IsMulti, Group>) {
  const { value, isMulti } = props.selectProps;
  // @ts-expect-error selectProps can't infer `online` here.
  const online: boolean = value?.online;

  return (
    <components.ValueContainer {...props}>

        {isMulti ? null : <StatusCircle online={online} />}
        {children}

    </components.ValueContainer>
  );
}

function Option<
  IsMulti extends boolean = false,
  Group extends GroupBase<PersonOption> = GroupBase<PersonOption>
>({ children, ...props }: OptionProps<PersonOption, IsMulti, Group>) {
  return (
    <components.Option {...props}>

        <StatusCircle online={Boolean(props.data?.online)} />
        {children}
        {/* @ts-expect-error selectProps can't infer `value` here. */}
        {props.selectProps.value?.id === props.data.id && (
          <CheckIcon className="h-5 w-5" aria-hidden="true" />
        )}

    </components.Option>
  );
}

const Template: ComponentStory<typeof Select> = ({
  inputId = 'react-select',
  ...props
}) => {
  const [value, setValue] = React.useState<PersonOption | null>(people[0]);

  return (

      <Field htmlFor={inputId} label="Assigned to">
        {/* @ts-ignore */}
        <Select<PersonOption>
          {...props}
          inputId={inputId}
          components={{ ValueContainer, Option }}
          options={people}
          getOptionLabel={(option) => option.name}
          getOptionValue={(option) => String(option.id)}
          value={value}
          onChange={(newValue) => setValue(newValue)}
        />
      </Field>
      {value && !value.online ? (

User {value.name} is currently offline.

      ) : undefined}

  );
};

export const Tailwind = Template.bind({});
Tailwind.args = {
  ...omit(defaultArgs, ['defaultValue', 'isMulti', 'options']),
};


text:
Awesome Scala
=============

A curated list of awesome Scala frameworks, libraries and software. Inspired by [awesome-python](https://github.com/vinta/awesome-python).

- [Awesome Scala](#awesome-scala)
    - [Database](#database)
    - [Web Frameworks](#frameworks)
    - [Authentication](#authentication)
    - [Testing](#testing)
    - [JSON Manipulation](#json-manipulation)
    - [Science and Data Analysis](#science-and-data-analysis)
    - [Big Data](#big-data)
    - [Modularization and Dependency Injection](#modularization-and-dependency-injection)
    - [Extensions](#extensions)
    - [Android](#android)
- [Contributing](#contributing)

## Database

*Database access libraries in Scala.*

* [ScalikeJDBC](https://github.com/scalikejdbc/scalikejdbc) - A tidy SQL-based DB access library for Scala developers.
* [Slick](https://github.com/slick/slick) - Modern database query and access library for Scala.
* [Squeryl](https://github.com/squeryl/squeryl) - A Scala DSL for talking with databases with minimum verbosity and maximum type safety.
* [Activate](https://github.com/fwbrasil/activate) - Pluggable object persistence in Scala.
* [Scala ActiveRecord](https://github.com/aselab/scala-activerecord) - ORM library for scala, inspired by ActiveRecord of Ruby on Rails.

## Web Frameworks

*Scala frameworks for web development.*

* [Play](https://github.com/playframework/playframework) - Makes it easy to build scalable, fast and real-time web applications with Java & Scala.
* [Skinny Framework](https://github.com/skinny-framework/skinny-framework) - A full-stack web app framework upon Scalatra for rapid Development in Scala.
* [Scalatra](https://github.com/scalatra/scalatra) - Tiny Scala high-performance, async web framework, inspired by Sinatra.
* [Lift](https://github.com/lift/framework) - Secure and powerful full stack web framework.
* [Spray](https://github.com/spray/spray) - A suite of scala libraries for building and consuming RESTful web services on top of Akka.
* [Finatra](https://github.com/twitter/finatra) - A sinatra-inspired web framework for scala, running on top of Finagle.
* [Blue Eyes](https://github.com/jdegoes/blueeyes) - A lightweight Web 3.0 framework for Scala, featuring a purely asynchronous architecture, extremely high-performance, massive scalability, high usability, and a functional, composable design.
* [Reactive](https://github.com/nafg/reactive) - FRP and web abstractions, which can be plugged into any web framework (currently only has bindings for Lift)

## Authentication

*Libraries for implementing authentications schemes.*

* [scala-oauth2-provider](https://github.com/nulab/scala-oauth2-provider) - OAuth 2.0 server-side implementation written in Scala.
* [SecureSocial](https://github.com/jaliss/securesocial) - A module that provides OAuth, OAuth2 and OpenID authentication for Play Framework applications.
* [play2-auth](https://github.com/t2v/play2-auth) - Play2.x Authentication and Authorization module.

## Testing

*Libraries for code testing.*

* [ScalaCheck](https://github.com/rickynils/scalacheck) - Property-based testing for Scala.
* [ScalaTest](https://github.com/scalatest/scalatest) - A testing tool for Scala and Java developers.
* [Specs2](https://github.com/etorreborre/specs2) - Software Specifications for Scala.

## JSON Manipulation

*Libraries for work with json.*

* [json4s](https://github.com/json4s/json4s) - project aims to provide a single AST to be used by other scala json libraries.
* [jerkson](https://github.com/codahale/jerkson) - a Scala wrapper for Jackson
* [spray-json](https://github.com/spray/spray-json) -  lightweight, clean and efficient JSON implementation in Scala.
* [argonaut](http://argonaut.io/) - Purely Functional JSON in Scala.
* [jackson-module-scala](https://github.com/FasterXML/jackson-module-scala) - Add-on module for Jackson to support Scala-specific datatypes

## Science and Data Analysis

*Libraries for scientific computing, data analysis and numerical processing.*

* [Breeze](https://github.com/scalanlp/breeze) - Breeze is a numerical processing library for Scala.
* [MLLib](https://spark.apache.org/mllib/) - Machine Learning framework for Spark
* [Spire](https://github.com/non/spire) - Powerful new number types and numeric abstractions for Scala.
* [Algebird](https://github.com/twitter/algebird) - Abstract Algebra for Scala.
* [FACTORIE](https://github.com/factorie/factorie) - A toolkit for deployable probabilistic modeling, implemented as a software library in Scala.
* [scala_prob](https://github.com/urso/scala_prob) - Scala embedded probabilistic programing library using delimited continuations (VERY Experimental).
* [probability-monad](https://github.com/jliszka/probability-monad) - Probability Distribution Monad in Scala.

## Big Data
* [Spark](http://spark.apache.org/) - Lightning fast cluster computing - up to 100x faster than Hadoop for iterative algorithms (memory caching) and up to 10x faster than Hadoop for single-pass MapReduce jobs. Compatible with YARN-enabled Hadoop clusters, can run on Mesos and in stand-alone mode as well.
* [Scalding](https://github.com/twitter/scalding) - A Scala binding for the Cascading abstraction of Hadoop MapReduce.
* [Summingbird](https://github.com/twitter/summingbird) - An implementation of the "lambda architecture" as a software abstraction - a single API for Hadoop and Storm.

## Modularization and Dependency Injection

*Modularization of applications, dependency injection, etc.*

* [Domino](https://github.com/helgoboss/domino) - Write elegant OSGi bundle activators in Scala.
* [Scaldi](https://github.com/scaldi/scaldi) - Lightweight Scala Dependency Injection Library.
* [MacWire](https://github.com/adamw/macwire) - Scala Macro to generate wiring code for class instantiation. DI container replacement.
* [SubCut](https://github.com/dickwall/subcut) - Scala Uniquely Bound Classes Under Traits.

## Extensions

*Scala extensions.*

* [Scalaz](https://github.com/scalaz/scalaz) - An extension to the core Scala library for functional programming.
* [Shapeless](https://github.com/milessabin/shapeless) - A type class and dependent type based generic programming library for Scala.

## Android

*Scala libraries and wrappers for Android development.*

* [Scaloid](https://github.com/pocorall/scaloid) - Less painful Android development with Scala.
* [Macroid](https://github.com/macroid/macroid) - A modular functional UI language for Android.
* [sbt-android-plugin](https://github.com/jberkel/android-plugin) - A sbt plugin for Android development in Scala.

# Contributing

Your contributions are always welcome! Please submit a pull request or create an issue to add a new framework, library or software to the list.


text:
// DFFDEVAL.cpp : implementation file
//
// Copyright (c) 2015 by Andrew W. Phillips
//
// This file is distributed under the MIT license, which basically says
// you can do what you want with it and I take no responsibility for bugs.
// See http://www.opensource.org/licenses/mit-license.php for full details.
//

#include "stdafx.h"

#include "hexedit.h"
#include "HexEditDoc.h"
#include "DataFormatView.h"
#include "DFFDEval.h"
#include "DFFDMisc.h"
#include "resource.hm"      // Help IDs
#include "HelpID.hm"            // User defined help IDs

#include <HtmlHelp.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CDFFDEval dialog

CDFFDEval::CDFFDEval(CXmlTree::CElt *pp, signed char parent_type,
				 CWnd* pParent /*=NULL*/)
	: CDialog(CDFFDEval::IDD, pParent), saved_(pp->GetOwner())
{
	modified_ = false;
	first_ = false;                     // Default to first (see SetPosition())

	pelt_ = pp;
	parent_type_ = parent_type;

	saved_.SaveKids(pelt_);
	saved_mod_flag_ = pelt_->GetOwner()->IsModified();
	show_prev_next_ = !pParent->IsKindOf(RUNTIME_CLASS(CDataFormatView)) &&
					  (parent_type == CHexEditDoc::DF_FILE ||
					   parent_type == CHexEditDoc::DF_STRUCT ||
					   parent_type == CHexEditDoc::DF_DEFINE_STRUCT ||
					   parent_type == CHexEditDoc::DF_SWITCH ||
					   parent_type == CHexEditDoc::DF_UNION);

	pos_.x = pos_.y = -30000;
	pexpr_menu_ = NULL;

	//{{AFX_DATA_INIT(CDFFDEval)
	expr_ = _T("");
	display_error_ = 0;
	display_result_ = 0;
	comment_ = _T("");
	//}}AFX_DATA_INIT
}

CDFFDEval::~CDFFDEval()
{
	if (pexpr_menu_ != NULL)
	{
		// Destroy the menu and free the memory
		pexpr_menu_->DestroyMenu();
		delete pexpr_menu_;
	}
}

void CDFFDEval::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDFFDEval)
	DDX_Control(pDX, ID_DFFD_PREV, ctl_prev_);
	DDX_Control(pDX, ID_DFFD_NEXT, ctl_next_);
	DDX_Text(pDX, IDC_DFFD_EXPR, expr_);
	DDX_Check(pDX, IDC_DFFD_DISPLAY_ERROR, display_error_);
	DDX_Check(pDX, IDC_DFFD_DISPLAY_RESULT, display_result_);
	DDX_Text(pDX, IDC_DFFD_COMMENTS, comment_);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_DFFD_EXPR, ctl_expr_);
	DDX_Control(pDX, IDC_DFFD_EXPR_VAR, ctl_expr_var_);
}

BEGIN_MESSAGE_MAP(CDFFDEval, CDialog)
	//{{AFX_MSG_MAP(CDFFDEval)
	ON_BN_CLICKED(ID_DFFD_NEXT, OnNext)
	ON_BN_CLICKED(ID_DFFD_PREV, OnPrev)
	ON_EN_CHANGE(IDC_DFFD_EXPR, OnChange)
	ON_BN_CLICKED(IDC_DFFD_DISPLAY_ERROR, OnChange)
	ON_BN_CLICKED(IDC_DFFD_DISPLAY_RESULT, OnChange)
	ON_EN_CHANGE(IDC_DFFD_COMMENTS, OnChange)
	ON_WM_HELPINFO()
	//}}AFX_MSG_MAP
	ON_WM_CONTEXTMENU()
	ON_MESSAGE(WM_KICKIDLE, OnKickIdle)
	ON_BN_CLICKED(ID_DFFD_HELP, OnHelp)
	ON_BN_CLICKED(IDC_DFFD_EXPR_VAR, OnGetExprVar)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDFFDEval message handlers

BOOL CDFFDEval::OnInitDialog()
{
	CDialog::OnInitDialog();
	SetIcon(AfxGetApp()->LoadIcon(IDI_EVAL), TRUE);

	// If window position specified
	if (pos_.y != -30000)
	{
		CRect rr;               // Rectangle where we will put the dialog
		GetWindowRect(&rr);

		// Move to where it was when it was last closed
		rr.OffsetRect(pos_.x - rr.left, pos_.y - rr.top);
		(void)::NeedsFix(rr);  // Make sure its visible

		MoveWindow(&rr);
	}

	if (!show_prev_next_)
	{
		// Hide << and >> (previous/next) buttons
		ctl_prev_.ShowWindow(SW_HIDE);
		ctl_next_.ShowWindow(SW_HIDE);
	}
	else
	{
		CXmlTree::CElt ee;
		if (parent_type_ == CHexEditDoc::DF_SWITCH)
			ee = pelt_->GetParent();
		else
			ee = *pelt_;
		ee--;
		ctl_prev_.EnableWindow(!ee.IsEmpty());

		if (parent_type_ == CHexEditDoc::DF_SWITCH)
			ee = pelt_->GetParent();
		else
			ee = *pelt_;
		++ee;
		ctl_next_.EnableWindow(!ee.IsEmpty());
	}

	load_data();

	// Set up menu that allows the user to choose any valid variable name
	pexpr_menu_ = make_var_menu_tree(*pelt_);
	ctl_expr_var_.m_hMenu = pexpr_menu_->GetSafeHmenu();
	ctl_expr_var_.m_bOSMenu = TRUE;
	ctl_expr_var_.m_bStayPressed = TRUE;
	ctl_expr_var_.m_bRightArrow = TRUE;
	ctl_expr_.SetSel(0, -1);           // Select all so a var selection (see OnGetConditionVar) replaces current contents
	return TRUE;
}

void CDFFDEval::OnCancel()
{
	pelt_->DeleteAllChildren();
	saved_.InsertKids(pelt_);
	pelt_->GetOwner()->SetModified(saved_mod_flag_);

	CDialog::OnCancel();
}

void CDFFDEval::OnOK()
{
	if (modified_)
	{
		if (!check_data())
			return;

		save_data();
	}

	CDialog::OnOK();
}

void CDFFDEval::OnNext()
{
	// Does the same as OnOK but returns ID_DFFD_NEXT to indicate
	// that the next sibling should now be edited
	if (modified_)
	{
		if (!check_data())
			return;

		save_data();
	}

	// Save position so sibling node's dialog can be put in the same place
	pos_ = update_posn(this);

	CDialog::EndDialog(ID_DFFD_NEXT);
}

void CDFFDEval::OnPrev()
{
	// Does the same as OnOK but returns ID_DFFD_PREV to indicate
	// that the previous sibling should now be edited
	if (modified_)
	{
		if (!check_data())
			return;

		save_data();
	}

	// Save position so sibling node's dialog can be put in the same place
	pos_ = update_posn(this);

	CDialog::EndDialog(ID_DFFD_PREV);
}

LRESULT CDFFDEval::OnKickIdle(WPARAM, LPARAM lCount)
{
	return FALSE;
}

void CDFFDEval::OnChange()
{
	modified_ = true;
}

void CDFFDEval::OnGetExprVar()
{
	if (ctl_expr_var_.m_nMenuResult != 0)
	{
		CString strVar = get_menu_text(pexpr_menu_, ctl_expr_var_.m_nMenuResult);
		ASSERT(!strVar.IsEmpty());      // The selected menu item should be found in the menu tree

		// Put the var name into the "expr" control
		for (int ii = 0; ii < strVar.GetLength (); ii++)
			ctl_expr_.SendMessage(WM_CHAR, (TCHAR)strVar[ii]);
		ctl_expr_.SetFocus();
		modified_ = true;
	}
}

void CDFFDEval::load_data()
{
	expr_ = pelt_->GetAttr("expr");
	display_error_  = pelt_->GetAttr("display_error").CompareNoCase("true") == 0 ? 1 : 0;
	display_result_ = pelt_->GetAttr("display_result").CompareNoCase("true") == 0 ? 1 : 0;
	comment_ = pelt_->GetAttr("comment");

	UpdateData(FALSE);
}

bool CDFFDEval::check_data()
{
	// Get values from the controls and validate them
	UpdateData();

	if (expr_.IsEmpty())
	{
		TaskMessageBox("Expression Not Specified",
			"Please enter an expression to be evaluated.\n\n"
			"This can simply be the name of a field or variable or "
			"a more complex expression.");
		GetDlgItem(IDC_DFFD_EXPR)->SetFocus();
		return false;
	}

	return true;
}

void CDFFDEval::save_data()
{
	// Save data to XML element node
	pelt_->SetAttr("expr", expr_);
	pelt_->SetAttr("display_error", display_error_ ? "true" : "false");
	pelt_->SetAttr("display_result", display_result_ ? "true" : "false");
	pelt_->SetAttr("comment", comment_);
}

void CDFFDEval::OnHelp()
{
	// Display help for this page
	if (!::HtmlHelp(AfxGetMainWnd()->m_hWnd, theApp.htmlhelp_file_, HH_HELP_CONTEXT, HIDD_DFFD_EVAL))
		AfxMessageBox(AFX_IDP_FAILED_TO_LAUNCH_HELP);
}

static DWORD id_pairs[] = {
	IDC_DFFD_EXPR, HIDC_DFFD_EXPR,
	IDC_DFFD_EXPR_VAR, HIDC_DFFD_EXPR_VAR,
	IDC_DFFD_DISPLAY_ERROR, HIDC_DFFD_DISPLAY_ERROR,
	IDC_DFFD_DISPLAY_RESULT, HIDC_DFFD_DISPLAY_RESULT,
	IDC_DFFD_COMMENTS, HIDC_DFFD_COMMENTS,
	ID_DFFD_PREV, HID_DFFD_PREV,
	ID_DFFD_NEXT, HID_DFFD_NEXT,
	0,0
};

BOOL CDFFDEval::OnHelpInfo(HELPINFO* pHelpInfo)
{
	theApp.HtmlHelpWmHelp((HWND)pHelpInfo->hItemHandle, id_pairs);
	return TRUE;
}

void CDFFDEval::OnContextMenu(CWnd* pWnd, CPoint point)
{
	theApp.HtmlHelpContextMenu(pWnd, id_pairs);
}


text:
/*
 * @addtogroup test_aon_basic_operations
 * @{
 * @defgroup t_aon_periodic_timer test_aon_periodic_timer
 * @brief TestPurpose: verify AON timer works well
 * @details
 * - Test Steps
 *   -# Start AON timer and wait for the register change to propagate.
 *   -# Set timer to alarm every second.
 *   -# Sleep for a long time to wait for the alarm invoked.
 * - Expected Results
 *   -# AON counter runs at 32768Hz, which means the counter will decrease
 *	32768 in one second. Set AONT down counter initial value register to
 *	32768, so the alarm will be invoked every second.
 *
 *	Sleep for a little longer than 3 seconds, the timer ISR is expected
 *	to be invoked 3 times.
 * @}
 */

#include "test_aon.h"

#define ALARM_CNT 32768 /* about 1s */
#define SLEEP_TIME 3050 /* a little longer than 3s */

static volatile int actual_alarm_cnt;

static void aon_timer_callback(struct device *dev, void *user_data)
{
	TC_PRINT("Periodic timer callback invoked: %u\n", counter_read(dev));

	/* verify counter_get_pending_int() */
	if (counter_get_pending_int(dev)) {
		TC_PRINT("Counter interrupt is pending\n");
		actual_alarm_cnt++;
	}
}

static int test_timer(void)
{
	u32_t dummy_data = 30;
	int expected_alarm_cnt = 0;
	struct device *aon_timer = device_get_binding(AON_TIMER);

	if (!aon_timer) {
		TC_PRINT("Cannot get AON Timer device\n");
		return TC_FAIL;
	}

	/* verify counter_start() */
	if (counter_start(aon_timer)) {
		TC_PRINT("Fail to start AON Timer device\n");
		return TC_FAIL;
	}

	/*
	 * The AON counter runs from the RTC clock at 32KHz (rather than
	 * the system clock which is 32MHz) so we need to spin for a few cycles
	 * allow the register change to propagate.
	 */
	k_sleep(10);
	TC_PRINT("Always-on timer started\n");

	/* verify counter_set_alarm() */
	if (counter_set_alarm(aon_timer, aon_timer_callback,
			      ALARM_CNT, (void *)&dummy_data)) {
		TC_PRINT("Fail to set alarm for AON Timer\n");
		return TC_FAIL;
	}

	/* long delay for the alarm and callback to happen */
	k_sleep(SLEEP_TIME);

	if (counter_set_alarm(aon_timer, NULL, 0, NULL)) {
		TC_PRINT("Periodic timer can not turn off\n");
		return TC_FAIL;
	}

	expected_alarm_cnt = (SLEEP_TIME/1000) / (32768/ALARM_CNT);

	TC_PRINT("expected_alarm_cnt = %d\n", expected_alarm_cnt);
	TC_PRINT("actual_alarm_cnt = %d\n", actual_alarm_cnt);

	if (actual_alarm_cnt != expected_alarm_cnt) {
		TC_PRINT("actual_alarm_cnt doesn't match expected_alarm_cnt\n");
		return TC_FAIL;
	}
	/*
	 * arduino_101 loader assumes the counter is running.
	 * If the counter is stopped, the next app you flash in
	 * cannot start without a hard reset or power cycle.
	 * So let's leave the counter in running state.
	 */
	return TC_PASS;
}

void test_aon_periodic_timer(void)
{
	zassert_true(test_timer() == TC_PASS, NULL);
}


text:
module Viewable extend ActiveSupport::Concern
    module ClassMethods
        def schema(church)
            FieldSchema.find_by(church: church, applies_to: self.name.downcase) || FieldSchema.new(church: church, applies_to: self.name.downcase)
        end

        def where_view(view)
            matches = self.where(church: view.church)
            schema = self.schema(view.church)
            if !view.filters.nil?
                values = []
                sql = process_group(view.filters, values, false, schema)
                if (!sql.blank?)
                    matches = matches.where(values.unshift sql)
                end
            end
            matches
        end

        private
        def test()
            throw "FAIL!!!!"
        end
        def process_group(group, values, has_condition, schema)
            sql = ""
            group.each do |rule|
                if (!sql.blank?)
                    sql += rule['logical_operator'] == 'AND' ? ' AND ' : ' OR '
                end
                if rule['condition'].is_a? Array
                    sql += process_group(rule['condition'], values, false, schema)
                else
                    sql += process_rule(rule, values, false, schema)
                end
            end
            sql.blank? ? sql : "(#{sql})"
        end

        def process_rule(rule, values, has_condition, schema)
            sql = ""
            condition = rule['condition']
            field_name = condition['field']
            operator = as_sql_operator(condition['operator'])
            value = as_sql_value(condition['operator'], condition['filterValue'] ? condition['filterValue'][0] : nil)

            if schema.has_field_with_id? field_name
                sql += "fields ->> ? #{operator} ?"
                values.push field_name
                values.push value
                has_condition = true
            elsif column_names.include?(field_name)
                sql += "#{field_name} #{operator} ?"
                values.push value
                has_condition = true
            else
                throw "Invalid field name"
            end
            sql
        end

        def as_sql_operator(condition_operator)
            case condition_operator
            when 'equal', 'is_empty'
                '='
            when 'begins_with', 'contains', 'ends_with'
                'LIKE'
            when 'not_begins_with', 'not_contains', 'not_ends_with'
                'NOT LIKE'
            when 'not_equal', 'not_is_empty'
                '!='
            else
                throw 'Invalid operator'
            end
        end

        def as_sql_value(condition_operator, raw_value)
            case condition_operator
            when 'begins_with', 'not_begins_with'
                "#{raw_value}%"
            when 'contains', 'not_contains'
                "%#{raw_value}%"
            when 'ends_with', 'not_ends_with'
                "%#{raw_value}"
            when 'is_empty', 'not_is_empty'
                ''
            else
                raw_value
            end
        end
    end
end


text:
'use strict';

angular
    .module('app.components', [
        'app.components.core',
        'app.components.toolbar',
        'app.components.sign',
        'app.components.goods',
        'app.shared'
    ]);


text:
package org.orecruncher.dsurround.capabilities;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.orecruncher.dsurround.ModInfo;
import org.orecruncher.dsurround.capabilities.entitydata.EntityData;
import org.orecruncher.dsurround.capabilities.entitydata.EntityDataTables;
import org.orecruncher.dsurround.capabilities.entitydata.IEntityData;
import org.orecruncher.dsurround.capabilities.entitydata.IEntityDataSettable;
import org.orecruncher.dsurround.network.Network;
import org.orecruncher.dsurround.network.PacketEntityData;
import org.orecruncher.lib.capability.CapabilityProviderSerializable;
import org.orecruncher.lib.capability.CapabilityUtils;
import org.orecruncher.lib.capability.SimpleStorage;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public final class CapabilityEntityData {

	@CapabilityInject(IEntityData.class)
	public static final Capability<IEntityData> ENTITY_DATA = null;
	public static final ResourceLocation CAPABILITY_ID = new ResourceLocation(ModInfo.MOD_ID, "data");

	public static void register() {
		CapabilityManager.INSTANCE.register(IEntityData.class, new SimpleStorage<>(), EntityData::new);
	}

	@Nullable
	public static IEntityData getCapability(@Nonnull final Entity entity) {
		return CapabilityUtils.getCapability(entity, CapabilityEntityData.ENTITY_DATA, null);
	}

	@Nonnull
	public static ICapabilityProvider createProvider(final IEntityData data) {
		return new CapabilityProviderSerializable<>(ENTITY_DATA, null, data);
	}

	@EventBusSubscriber(modid = ModInfo.MOD_ID)
	public static class EventHandler {

		/*
		 * Attach the capability to the Entity when it is created.
		 */
		@SubscribeEvent
		public static void attachCapabilities(final AttachCapabilitiesEvent<Entity> event) {
			if (event.getObject() instanceof EntityLiving) {
				final EntityData emojiData = new EntityData((EntityLiving) event.getObject());
				event.addCapability(CAPABILITY_ID, createProvider(emojiData));
			}
		}

		/*
		 * Event generated when a player starts tracking an Entity. Need to send an
		 * initial sync to the player.
		 */
		@SubscribeEvent
		public static void trackingEvent(@Nonnull final PlayerEvent.StartTracking event) {
			if (event.getTarget() instanceof EntityLiving) {
				final IEntityData data = event.getTarget().getCapability(ENTITY_DATA, null);
				if (data != null) {
					Network.sendToPlayer((EntityPlayerMP) event.getEntityPlayer(), new PacketEntityData(data));
				}
			}
		}

		/*
		 * Called when an entity is being updated. Need to evaluate new states.
		 */
		@SubscribeEvent()
		public static void livingUpdate(@Nonnull final LivingUpdateEvent event) {
			final Entity entity = event.getEntity();
			final World world = entity.getEntityWorld();
			// Don't tick if this is the client thread. We only check 4 times a
			// second as if that is enough :)
			if (world.isRemote || (entity.ticksExisted % 5) != 0)
				return;
			final IEntityDataSettable data = (IEntityDataSettable) getCapability(event.getEntity());
			if (data != null) {
				EntityDataTables.assess(data);
				data.sync();
			}
		}
	}

}


text:
"""
Copyright (c) 2022 The Orbit Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
"""

from absl import app

from core.orbit_e2e import E2ETestSuite
from test_cases.connection_window import FilterAndSelectFirstProcess, ConnectToStadiaInstance
from test_cases.capture_window import Capture, CheckTimers
from test_cases.symbols_tab import WaitForLoadingSymbolsAndCheckModuleState, FilterAndHookFunction
from test_cases.live_tab import VerifyScopeTypeAndHitCount
"""Instrument a single function using user space instrumentation on Silenus.

Before this script is run there needs to be a gamelet reserved and our version
of "triangle.exe" with the `Render` function made `__declspec(noinline)` has to
be started.

The script requires absl and pywinauto. Since pywinauto requires the bitness of
the python installation to match the bitness of the program under test, it needs
to be run from 64 bit python.

This automation script covers a basic workflow:
 - connect to a gamelet, select a process running on Silenus, load debug symbols
 - instrument a function
 - take a capture with Orbit's user space dynamic instrumentation
 - verify the hooked function is recorded
"""

def main(argv):
    test_cases = [
        ConnectToStadiaInstance(),
        FilterAndSelectFirstProcess(process_filter="triangle.exe"),
        WaitForLoadingSymbolsAndCheckModuleState(module_search_string="triangle.exe"),
        FilterAndHookFunction(function_search_string="Render{ }triangle.exe"),
        Capture(user_space_instrumentation=True),
        CheckTimers(track_name_filter="triangle.exe", require_all=False),
        VerifyScopeTypeAndHitCount(scope_name="Render",
                                   scope_type="D",
                                   min_hits=700,
                                   max_hits=70000),
    ]
    suite = E2ETestSuite(test_name="User Space Instrumentation on Silenus", test_cases=test_cases)
    suite.execute()

if __name__ == '__main__':
    app.run(main)


text:
require 'spree_core'
require 'spree_ecard/engine'
require "spree_ecard/version"

module SpreeEcard
  class << self
    attr_accessor :configuration
  end

  def self.configure
    self.configuration ||= Configuration.new
    yield(configuration)
  end

  class Configuration
    attr_accessor :currency, :country, :language, :charset, :autodeposit, :hashalgorithm, :transparentpages,
                  :merchantid, :password, :paymenttype

    def initialize
      @option = 'default_option'
    end
  end

end


text:
package seedu.task.logic;

import javafx.collections.ObservableList;

import seedu.task.commons.core.ComponentManager;
import seedu.task.commons.core.LogsCenter;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.CommandResult;
import seedu.task.logic.commands.UndoableCommand;
import seedu.task.logic.parser.ParseSwitcher;
import seedu.task.model.Model;
import seedu.task.model.task.ReadOnlyTask;

import java.util.Arrays;
import java.util.HashSet;
import java.util.logging.Logger;

/**
 * The main LogicManager of the app.
 */
public class LogicManager extends ComponentManager implements Logic {
    private final Logger logger = LogsCenter.getLogger(LogicManager.class);

    private final Model model;
    private final ParseSwitcher parser;
    private UndoableCommand previousCommand;

    public LogicManager(Model model) {
        this.model = model;
        this.parser = new ParseSwitcher(model.getAliasMap());
        this.previousCommand = null;
    }

    @Override
    public CommandResult execute(String commandText) {
        logger.info("----------------[USER COMMAND][" + commandText + "]");
        Command command = parser.parseCommand(commandText);
        command.setData(model, previousCommand);
        CommandResult result = command.execute();
        setPreviousCommand(result.isSuccessful, command);
        return result;
    }

    @Override
    public ObservableList<ReadOnlyTask> getFilteredTaskList() {
        return model.getFilteredTaskList();
    }

    //@@author A0141052Y
    @Override
    public void updateTaskListFilter(String keyword) {
        model.updateFilteredTaskList(new HashSet<String>(Arrays.asList(keyword)));
    }

    private void setPreviousCommand(boolean isSuccessful, Command command) {
        if (isSuccessful && command instanceof UndoableCommand) {
            this.previousCommand = (UndoableCommand) command;
        } else {
            this.previousCommand = null;
        }
    }
}