text:
package com.gizwits.opensource.appkit.ConfigModule;

import com.gizwits.opensource.appkit.CommonModule.GosDeploy;
import com.gizwits.opensource.appkit.view.GifView;
import com.gizwits.opensource.smartlight.R;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class GosDeviceResetActivity extends GosConfigModuleBaseActivity implements OnClickListener {

	/** The cb Select */
	CheckBox cbSelect;

	/** The tv Select */
	TextView tvSelect;

	/** The btn Next */
	Button btnNext;

	/** The flag */
	String flag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actvity_gos_device_reset);
		// 设置ActionBar
		setActionBar(true, true, R.string.reset_device);

		initView();
		initEvent();
	}

	private void initView() {
		cbSelect = (CheckBox) findViewById(R.id.cbSelect);
		tvSelect = (TextView) findViewById(R.id.tvSelect);
		btnNext = (Button) findViewById(R.id.btnNext);

		/** 加载Gif */
		GifView gif = (GifView) findViewById(R.id.softreset);
		gif.setMovieResource(R.drawable.resetsoftap);

		/** 加载标志位 */
		flag = getIntent().getStringExtra("flag").toString();

		// 配置文件部署
		btnNext.setBackgroundDrawable(GosDeploy.setButtonBackgroundColor());
		btnNext.setTextColor(GosDeploy.setButtonTextColor());

	}

	private void initEvent() {
		btnNext.setOnClickListener(this);
		tvSelect.setOnClickListener(this);
		btnNext.setClickable(false);
		btnNext.setBackgroundResource(R.drawable.button_shape_gray);

		cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					btnNext.setBackgroundDrawable(GosDeploy.setButtonBackgroundColor());
					btnNext.setClickable(true);
				} else {
					btnNext.setBackgroundResource(R.drawable.button_shape_gray);
					btnNext.setClickable(false);
				}

			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnNext:
			if (TextUtils.isEmpty(flag)) {
				Intent intent = new Intent(GosDeviceResetActivity.this, GosChooseDeviceActivity.class);
				startActivity(intent);
			}
			finish();

			break;

		case R.id.tvSelect:
			if (cbSelect.isChecked()) {
				cbSelect.setChecked(false);
			} else {
				cbSelect.setChecked(true);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			if (TextUtils.isEmpty(flag)) {
				Intent intent = new Intent(GosDeviceResetActivity.this, GosDeviceReadyActivity.class);
				startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			}
			this.finish();

			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (TextUtils.isEmpty(flag)) {
				Intent intent = new Intent(GosDeviceResetActivity.this, GosDeviceReadyActivity.class);
				startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			}
			this.finish();

		}
		return true;
	}
}


text:
import asyncio
import logging
import concurrent.futures

class EchoServer(object):
    """Echo server class"""

    def __init__(self, host, port, loop=None):
        self._loop = loop or asyncio.get_event_loop()
        self._server = asyncio.start_server(self.handle_connection, host=host, port=port)

    def start(self, and_loop=True):
        self._server = self._loop.run_until_complete(self._server)
        logging.info('Listening established on {0}'.format(self._server.sockets[0].getsockname()))
        if and_loop:
            self._loop.run_forever()

    def stop(self, and_loop=True):
        self._server.close()
        if and_loop:
            self._loop.close()

    @asyncio.coroutine
    def handle_connection(self, reader, writer):
        peername = writer.get_extra_info('peername')
        logging.info('Accepted connection from {}'.format(peername))
        while not reader.at_eof():
            try:
                data = yield from asyncio.wait_for(reader.readline(), timeout=10.0)
                writer.write(data)
            except concurrent.futures.TimeoutError:
                break
        writer.close()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    server = EchoServer('127.0.0.1', 2007)
    try:
        server.start()
    except KeyboardInterrupt:
        pass # Press Ctrl+C to stop
    finally:
        server.stop()

redpajama_set_name: RedPajamaGithub


text:
package org.dcm4cheri.hl7;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

/**
 * <description>
 *
 * @see <related>
 * @author  gunter zeilinger
 * @version $Revision: 3922 $ $Date: 2005-10-06 00:26:16 +0800 (周四, 06 10月 2005) $
 *
 */
class HL7FieldsImpl implements HL7Fields
{
   // Constants -----------------------------------------------------

   // Attributes ----------------------------------------------------
   protected final byte[] data;
   protected final int off;
   protected final int len;
   protected final byte[] delim;
   protected HL7Fields[] subFields = null;

   // Static --------------------------------------------------------
   static final HL7Fields NULL = new HL7Fields() {
      public String toString() {
         return "";
      }

      public String get(int index) {
         return "";
      }

      public int size() {
         return 0;
      }

      public String get(int[] index) {
         return "";
      }

      public int size(int index) {
         return 0;
      }

      public int size(int[] index) {
         return 0;
      }

      public void writeTo(ByteArrayOutputStream out) {
      }

      public void writeTo(int index, ByteArrayOutputStream out) {
      }
   };

   static HL7Fields newInstance(byte[] data, int off, int len, byte[] delim) {
      return len == 0 ? NULL : new HL7FieldsImpl(data, off, len, delim);
   }

   // Constructors --------------------------------------------------
   public HL7FieldsImpl(byte[] data, int off, int len, byte[] delim) {
      if (data.length < off + len) {
         throw new IllegalArgumentException("data.length[" + data.length
               + "] < off[" + off + "] + len [" + len + "]");
      }
      if (delim.length == 0) {
         throw new IllegalArgumentException("delim.length == 0");
      }
      this.data = data;
      this.off = off;
      this.len = len;
      this.delim = delim;
   }

   // Public --------------------------------------------------------

   public int size() {
      initSubFields();
      return subFields.length;
   }

   public int size(int index) {
     if (delim.length == 0) {
         throw new IllegalArgumentException("delim.length == 0");
     }
     initSubFields();
     return index < subFields.length ? subFields[index].size() : 0;
   }

   public int size(int[] index) {
      if (index.length > delim.length) {
         throw new IllegalArgumentException("index.length[" + index.length
               + "] > delim.length[" + delim.length + "]");
      }
      switch (index.length) {
         case 0:
            return size();
         case 1:
            return size(index[0]);
         default:
            initSubFields();
            if (index[0] >= subFields.length) {
               return 0;
            }
            int[] index_1 = new int[index.length-1];
            System.arraycopy(index, 1, index_1, 0, index_1.length);
            return subFields[index[0]].size(index_1);
      }
   }

   public void writeTo(ByteArrayOutputStream out) {
      out.write(data, off, len);
   }

   public void writeTo(int index, ByteArrayOutputStream out) {
      initSubFields();
      if (index < subFields.length) {
         subFields[index].writeTo(out);
      }
   }

   public String toString() {
       try {
           return new String(data, off, len, "ISO-8859-1");
       } catch (UnsupportedEncodingException e) {
           return new String(data, off, len);
       }
   }

   public String get(int index) {
     if (delim.length == 0) {
         throw new IllegalArgumentException("delim.length == 0");
     }
     initSubFields();
     return index < subFields.length ? subFields[index].toString() : "";
   }

   public String get(int[] index) {
      if (index.length > delim.length) {
         throw new IllegalArgumentException("index.length[" + index.length
               + "] > delim.length[" + delim.length + "]");
      }
      switch (index.length) {
         case 0:
            return toString();
         case 1:
            return get(index[0]);
         default:
            initSubFields();
            if (index[0] >= subFields.length) {
               return "";
            }
            int[] index_1 = new int[index.length-1];
            System.arraycopy(index, 1, index_1, 0, index_1.length);
            return subFields[index[0]].get(index_1);
      }
   }

   private void initSubFields() {
      if (subFields != null) {
         return;
      }

      int index = 0;
      for (int i = off, n = off + len; i < n; ++i) {
         if (data[i] == delim[0]) {
            ++index;
         }
      }
      subFields = new HL7Fields[index+1];
      byte[] delim_1 = new byte[delim.length-1];
      System.arraycopy(delim, 1, delim_1, 0, delim_1.length);
      index = 0;
      int left = off;
      for (int i = off, n = off + len; i < n; ++i) {
         if (data[i] == delim[0]) {
            subFields[index++] = newInstance(data, left, i - left, delim_1);
            left = i+1;
         }
      }
      subFields[index] = newInstance(data, left, off + len - left, delim_1);
   }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="3dp" />
    <solid android:color="#ffFFFf" />
    <padding
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp" />
    <size
        android:width="270dp"
        android:height="40dp" />
    <stroke
        android:width="1dp"
        android:color="#F5F5F5" />

    <item>
        <layer-list>
            <item
                android:right="10dp"
                android:top="5dp">
                <shape>
                    <corners android:radius="1dp" />
                    <solid android:color="@color/blue600" />
                </shape>
            </item>
        </layer-list>
    </item>
</shape>


text:
#include "tensorflow/compiler/xla/client/global_data.h"

#include <string>

#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {

GlobalData::GlobalData(ServiceInterface* parent, GlobalDataHandle handle)
    : handle_(handle), parent_(parent) {}

GlobalData::~GlobalData() {
  UnregisterRequest request;
  *request.mutable_data() = handle_;
  UnregisterResponse response;
  VLOG(1) << "requesting to unregister " << handle_.ShortDebugString();
  tensorflow::Status s = parent_->Unregister(&request, &response);
  VLOG(1) << "done with request";

  if (!s.ok()) {
    LOG(WARNING) << "failed to unregister " << handle_.ShortDebugString()
                 << "; continuing anyway...";
  }
}

}  // namespace xla


text:
.picker {
	-moz-user-select: none;
	-ms-user-select: none;
	-webkit-user-select: none;
	color: #000;
	font-size: 16px;
	line-height: 1.2;
	position: absolute;
	text-align: left;
	user-select: none;
	z-index: 10000;
}

.picker__input {
	cursor: default
}

.picker__input.picker__input--active {
	border-color: #0089ec
}

.picker__holder {
	-webkit-overflow-scrolling: touch;
	overflow-y: auto;
	width: 100%;
}

/*!
 * Classic picker styling for pickadate.js
 * Demo: http://amsul.github.io/pickadate.js
 */

.picker {
	width: 100%
}

.picker__holder {
	-moz-opacity: 0;
	-ms-filter: "alpha(Opacity=0)";
	-webkit-transform: translateY(-1em) perspective(600px) rotateX(10deg);
	background: #fff;
	border: 1px solid #aaa;
	border-bottom-width: 0;
	border-radius: 0 0 5px 5px;
	border-top-width: 0;
	box-sizing: border-box;
	filter: alpha(opacity=0);
	max-height: 0;
	max-width: 466px;
	min-width: 176px;
	opacity: 0;
	position: absolute;
	transform: translateY(-1em) perspective(600px) rotateX(10deg);
	transition: -webkit-transform .15s ease-out, opacity .15s ease-out, max-height 0s .15s, border-width 0s .15s;
	transition: transform .15s ease-out, opacity .15s ease-out, max-height 0s .15s, border-width 0s .15s
}

.picker__frame {
	padding: 1px
}

.picker__wrap {
	margin: -1px
}

.picker--opened .picker__holder {
	-moz-opacity: 1;
	-ms-filter: "alpha(Opacity=100)";
	-webkit-transform: translateY(0) perspective(600px) rotateX(0);
	border-bottom-width: 1px;
	border-top-width: 1px;
	box-shadow: 0 6px 18px 1px rgba(0, 0, 0, .12);
	filter: alpha(opacity=100);
	max-height: 25em;
	opacity: 1;
	transform: translateY(0) perspective(600px) rotateX(0);
	transition: -webkit-transform .15s ease-out, opacity .15s ease-out, max-height 0s, border-width 0s;
	transition: transform .15s ease-out, opacity .15s ease-out, max-height 0s, border-width 0s;
}


text:
package com.structurizr.view;

public enum Shape {

    Box,
    RoundedBox,
    Circle,
    Ellipse,
    Hexagon,
    Cylinder,
    Pipe,
    Person,
    Robot,
    Folder,
    WebBrowser,
    MobileDevicePortrait,
    MobileDeviceLandscape

}


text:
package com.sqisland.gce2retrofit;

import com.google.gson.JsonObject;

import java.util.List;

public class Method {
  public String id;
  public String path;
  public String httpMethod;
  public String description;
  public JsonObject parameters;
  public List<String> parameterOrder;
  public RequestOrResponse request;
  public RequestOrResponse response;

  public static class RequestOrResponse {
    public String $ref;
    public String parameterName;
  }
}


text:
package uk.gov.eastlothian.gowalk.ui;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import uk.gov.eastlothian.gowalk.R;
import uk.gov.eastlothian.gowalk.data.WalksContract;

public class LogBookSightingDetailActivity extends MainMenuActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_book_sighting_detail);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new LogBookSightingDetailFragment())
                    .commit();
        }
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class LogBookSightingDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{

        static final int SIGHTING_ID = 0;

        ViewGroup rootView;
        ImageView imageView;
        TextView dataTimeTextView;
        TextView locationTextView;
        TextView weatherTextView;
        Button deleteButton;
        long logEntryId;

        public LogBookSightingDetailFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            rootView = (ViewGroup) inflater.inflate(R.layout.fragment_log_book_sighting_detail, container, false);

            // bind the items in the view
            imageView = (ImageView) rootView.findViewById(R.id.log_book_sighting_image);
            dataTimeTextView = (TextView) rootView.findViewById(R.id.log_book_sighting_datetime);
            locationTextView = (TextView) rootView.findViewById(R.id.log_book_sighting_place);
            weatherTextView = (TextView) rootView.findViewById(R.id.log_book_sighting_weather);
            deleteButton = (Button) rootView.findViewById(R.id.log_book_sighting_delete_button);

            // start loading the log entry
            getLoaderManager().initLoader(SIGHTING_ID, null, this);

            return rootView;
        }

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            logEntryId = getActivity().getIntent().getLongExtra("log_entry_id", -1);
            if( logEntryId != -1) {
                Uri uri = WalksContract.LogEntry.buildLogEntrysUri(logEntryId);
                Loader<Cursor> rtnCursor = new CursorLoader(getActivity(), uri, null, null, null, null);
                return rtnCursor;
            } else {
                return null; // TODO: How should we handle this? Exception?
            }
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                int latIdx = cursor.getColumnIndex(WalksContract.LogEntry.COLUMN_LAT);
                int lngIdx = cursor.getColumnIndex(WalksContract.LogEntry.COLUMN_LNG);
                int dateTimeIdx = cursor.getColumnIndex(WalksContract.LogEntry.COLUMN_DATATIME);
                int weatherIdx = cursor.getColumnIndex(WalksContract.LogEntry.COLUMN_WEATHER);
                int imagePathIdx = cursor.getColumnIndex(WalksContract.LogEntry.COLUMN_IMAGE);

                String lat = cursor.getString(latIdx);
                String lng = cursor.getString(lngIdx);
                String dateTime = cursor.getString(dateTimeIdx);
                String weather = cursor.getString(weatherIdx);
                String imagePath = cursor.getString(imagePathIdx);

                SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    iso8601Format.parse(dateTime);
                    final Calendar calendar = iso8601Format.getCalendar();

                    SimpleDateFormat prettyFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
                    dateTime = prettyFormat.format(calendar.getTime());

                    dataTimeTextView.setText("Sighting at " + dateTime.split(" ")[0]
                                                   + " on " + dateTime.split(" ")[1]);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                weatherTextView.setText(weather);
                locationTextView.setText(lat + ", " + lng + "");

                // check if the file exists for the path
                File file = new File(imagePath);
                if(file.exists()) {
                    setImageView(imagePath);
                }
                // set up the camera button
                /*
                Button cameraButton = (Button) rootView.findViewById(R.id.log_book_sighting_camera_button);
                cameraButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                */

                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new AlertDialog.Builder(getActivity())
                                .setTitle("Delete entry")
                                .setMessage("Are you sure you want to delete this entry?")
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // continue with delete
                                        deleteLogEntry();
                                        Toast toast = Toast.makeText(getActivity(), "Sighting deleted", Toast.LENGTH_SHORT);
                                        toast.show();
                                        getActivity().finish();
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // do nothing
                                    }
                                })
                                .setIcon(R.drawable.ic_launcher)
                                .show();
                    }
                });
            }
        }

        private void deleteLogEntry() {
            // Log.d("BAB", "delete log entry" + logEntryId);
            getActivity().getContentResolver().delete(
                    WalksContract.LogEntry.CONTENT_URI,
                    "_id = ?",
                    new String[] {new Long(logEntryId).toString()});

        }

        private void setImageView(String path) {
            // TODO: Can this be done in asyc
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inPurgeable = true;

            Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
            imageView.setImageBitmap(bitmap);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    }
}


text:
var Path = require("path");
var _ = require("underscore");

var ModuleUtils = require("./utils/module_utils.js");
var ObjectUtils = require("./utils/object_utils.js");
var PathUtils = require("./utils/path_utils.js");

var withoutFingerprint = function(name) {
	return name.replace(/-\d+$/, "");
};

module.exports = {

	templates: null,

	cacheStore: null,

	minifiers: {},

	compilers: {},

	bundleOptions: {},

	bundles: {},

	setup: function(config) {
		var self = this;

		self.templates = ModuleUtils.requireAndSetup(config.plugins.template_handler, config);
		self.cacheStore = ModuleUtils.requireAndSetup(config.plugins.cache_store, config);

		_.each(config.plugins.compilers, function(value, key) {
			self.compilers[key] = ModuleUtils.requireAndSetup(value, config);
		});

		_.each(config.plugins.minifiers, function(value, key) {
			self.minifiers[key] = ModuleUtils.requireAndSetup(value, config);
		});

		self.bundles = _.extend(self.bundles, config.bundles);

		self.bundleOptions = _.extend(self.bundleOptions, config.asset_bundling);

	},

	compileAndMinify: function(template_path, template_extension, compiler, minifier, callback) {
		var self = this;

		if(!template_path) {
			return callback("Template path can't be null", null);
		}

		if (!minifier) {
			return callback("No minifier found", null);
		}

		self.templates.readTemplate(template_path, function(err, template_output) {
			if (err) {
				return callback(err, null);
			}

			if (compiler && compiler.input_extensions.indexOf(template_extension) > -1)	{
				compiler.compile(template_output, Path.join(self.templates.templateDir, template_path), function(err, compiled_output) {
					if(err) {
						return callback(err, null);
					}

					return minifier.minify(compiled_output, callback);
				});
			} else {
				return minifier.minify(template_output, callback);
			}
		});
	},

	prepareBundle: function(bundle, output_extension, callback) {
		var self = this;

		var compiler = self.compilers[output_extension];
		var minifier = self.minifiers[output_extension];

		var cloned_bundle_templates = bundle.slice(0);
		var minified_outputs = [];

		var fetch_compile_and_minify = function() {
			if (cloned_bundle_templates.length) {

				var current_template_path = cloned_bundle_templates.shift();
				var current_template_extension = PathUtils.getExtension(current_template_path);

				self.compileAndMinify(current_template_path, current_template_extension, compiler, minifier, function(err, minified_output) {
					if (!err) {
						minified_outputs.push(minified_output);
					}

					return fetch_compile_and_minify();
				});
			} else {
				return callback(minified_outputs.join(""));
			}
		};

		return fetch_compile_and_minify();
	},

	getContainedFilesInBundle: function(bundle_name, file_extension, callback) {
		var self = this;
		var defined_paths = self.bundles[bundle_name + file_extension];
		var resolved_paths = [];

		if (!defined_paths) {
			return callback("[Error: There's no Bundle for the given path]", null);
		} else {
			// create a copy of the paths
			defined_paths = defined_paths.slice(0);
		}

		var add_all_matching_paths = function(basename, extension_to_match, cb) {
			var dirPath = Path.dirname(basename);
			var matching_paths = [];

			self.templates.getTemplates(dirPath, function(err, template_paths) {
				if (err) {
					return cb(err, matching_paths);
				}

				_.each(template_paths, function(current_path_obj) {
					var current_path = current_path_obj.full_path;
					var current_ext = Path.extname(current_path);
					if (extension_to_match === "" || current_ext === extension_to_match) {
						matching_paths.push(current_path);
					}
				});

				return cb(null, matching_paths);
			});
		};

		var resolve_defined_paths = function(err, given_paths) {

			resolved_paths = resolved_paths.concat(given_paths);

			if (defined_paths.length) {
				var current_path = defined_paths.shift();
				var current_extension = Path.extname(current_path);
				var current_basename = PathUtils.getBasename(current_path, current_extension);

				if (self.isBundlePath(current_basename, current_extension)) {
					return self.getContainedFilesInBundle(current_basename, current_extension, resolve_defined_paths);
				}

				if (current_basename[current_basename.length - 1] === "*") {
					return add_all_matching_paths(current_basename, current_extension, resolve_defined_paths);
				}

				return resolve_defined_paths(null, current_path);
			}	else {
				return callback(null, resolved_paths);
			}
		};

		return resolve_defined_paths(null, []);
	},

	getBundle: function(request_basename, file_extension, request_options, callback) {
		var self = this;
		var bundle_name = withoutFingerprint(request_basename);
		var bundle_options = _.extend({}, self.bundleOptions);
		var bundle_header = bundle_options.header || {};

		self.getContainedFilesInBundle(bundle_name, file_extension, function(err, bundled_files) {

			if (err) {
				return callback(err, null);
			}

			var prepare_bundle_and_update_cache = function() {
				return self.prepareBundle(bundled_files, file_extension, function(minified_output) {
					return self.cacheStore.update(bundle_name, file_extension, ObjectUtils.cacheObj(minified_output, bundle_header), request_options, function(err, cache_obj) {
						bundle_options.header = cache_obj.options.header;
						return callback(null, { "body": minified_output, "modified": true, "options": bundle_options });
					});
				});
			};

			self.cacheStore.stat(bundle_name, file_extension, request_options, function(err, stat) {
				if (err) {
					return prepare_bundle_and_update_cache();
				}

				var cloned_bundled_files = bundled_files.slice(0);

				var check_for_modified = function() {
					if (cloned_bundled_files.length) {
						self.templates.getTemplate(cloned_bundled_files.shift(), function(err, template) {
							if (err) {
								return check_for_modified();
							}

							if (template.last_modified > stat.mtime) {
								return prepare_bundle_and_update_cache();
							} else {
								return check_for_modified();
							}
						});
					} else {
						return self.cacheStore.get(bundle_name, file_extension, ObjectUtils.cacheObj(null, bundle_header), request_options, function(err, cache_obj) {
							bundle_options.header = cache_obj.options.header;
							return callback(null, { "body": cache_obj.body, "modified": false, "options": bundle_options });
						});
					}
				};

				return check_for_modified();
			});

		});
	},

	statBundle: function(request_basename, file_extension, callback) {
		var self = this;
		var bundle_name = withoutFingerprint(request_basename);

		self.getContainedFilesInBundle(bundle_name, file_extension, function(err, bundled_files) {

			if (err) {
				return callback(err, null);
			}

			var bundle_mtime = null;

			var traverse_bundled_files = function() {
				if (bundled_files.length) {
					self.templates.getTemplate(bundled_files.shift(), function(err, template) {
						if (err) {
							return traverse_bundled_files();
						}

						var current_mtime = template.last_modified;
						if (current_mtime > bundle_mtime) {
							bundle_mtime = current_mtime;
						}

						return traverse_bundled_files();
					});
				} else {
					return callback(null, { "mtime": bundle_mtime });
				}
			};

			return traverse_bundled_files();
		});
	},

	touchBundles: function(after, complete) {
		var self = this;

		var collected_bundles = [];

		_.each(self.bundles, function(value, entry) {
			var extension = Path.extname(entry);
			var basename = entry.substr(0, entry.indexOf(extension));

			collected_bundles.push([ basename, extension ]);
		});

		var touch_next_bundle = function() {
			if (collected_bundles.length) {
				var params = collected_bundles.shift();

				//push the options
				params.push({});

				params.push(function(err, bundle_obj) {
					var bundle_path = params[0] + params[1];

					// create the fingerprinted bundle
					if (self.bundleOptions.fingerprint) {
						self.fingerprintBundle(bundle_path, after);
					}

					// set the bundle path only if the bundle is modified.
					// this is to let generator hooks to skip the callback if path is null.
					var path_to_notify = (bundle_obj.modified) ? bundle_path : null;
					after(path_to_notify, function() {
						return touch_next_bundle();
					});
				});

				return self.getBundle.apply(self, params);
			} else {
				return complete();
			}
		};

		return touch_next_bundle();
	},

	fingerprintBundle: function(bundle_path, callback) {
		var self = this;

		if (!bundle_path) {
			return callback();
		}

		var bundle_extension = PathUtils.getExtension(bundle_path);
		var bundle_basename = PathUtils.getBasename(bundle_path, bundle_extension);

		self.statBundle(bundle_basename, bundle_extension, function(err, stat) {
			if (err) {
				return callback();
			}

			var bundle_fingerprint = stat.mtime.getTime();
			var fingerprinted_bundle_path = bundle_basename + "-" + bundle_fingerprint;

			self.cacheStore.get(bundle_basename, bundle_extension, {}, null, function(err, bundle_content) {
				if (err) {
					return callback();
				}

				self.cacheStore.update(fingerprinted_bundle_path, bundle_extension, bundle_content, {}, function(err) {
					return callback(fingerprinted_bundle_path + bundle_extension, function() { });
				});
			});
		});
	},

	isBundlePath: function(basename, file_extension) {
		var self = this;

		var bundle_names = _.keys(self.bundles);

		var bundle_path = withoutFingerprint(basename) + file_extension;

		return (bundle_names.indexOf(bundle_path) >  -1);
	}

};


text:
package com.congtyhai.dms.Agency;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.congtyhai.adapter.C2C1Adapter;
import com.congtyhai.dms.BaseActivity;
import com.congtyhai.dms.R;
import com.congtyhai.model.api.C2C1Info;
import com.congtyhai.util.HAIRes;
import com.congtyhai.view.RecyclerTouchListener;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class C2OfC1Activity extends BaseActivity {

    private List<C2C1Info> agencyList ;
    private List<C2C1Info> agencyListTemp ;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private C2C1Adapter mAdapter;

    boolean isResult = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_c2_of_c1);
        createToolbar();
        ButterKnife.bind(this);
        agencyList = new ArrayList<>();
        agencyListTemp = new ArrayList<>();

        mAdapter = new C2C1Adapter(agencyList);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                C2C1Info info = agencyList.get(position);
                if (isResult) {
                    Intent returnIntent = new Intent();
                    returnIntent.putExtra("code", info.getCode());
                    returnIntent.putExtra("name", info.getName());
                    setResult(Activity.RESULT_OK,returnIntent);
                    finish();
                }
            }

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

            }
        }));

        Intent intent = getIntent();

        String code = intent.getStringExtra(HAIRes.getInstance().KEY_INTENT_TEMP);

        if("getcode".equals(code)) {
            isResult = true;
        }

        new ReadDataTask().execute();

    }

    private void makeRequest() {

        showpDialog();
        String user = prefsHelper.get(HAIRes.getInstance().PREF_KEY_USER, "");
        String token = prefsHelper.get(HAIRes.getInstance().PREF_KEY_TOKEN, "");
        Call<C2C1Info[]> call = apiInterface().getC2C1(user, token);
        call.enqueue(new Callback<C2C1Info[]>() {
            @Override
            public void onResponse(Call<C2C1Info[]> call, Response<C2C1Info[]> response) {
                if(response.body() != null) {
                    saveListC2OfC1(response.body());
                }
                hidepDialog();
                new ReadDataTask().execute();
            }

            @Override
            public void onFailure(Call<C2C1Info[]> call, Throwable t) {
                hidepDialog();
            }
        });
    }

    private class ReadDataTask extends AsyncTask<String, Integer, List<C2C1Info>> {
        protected List<C2C1Info> doInBackground(String... urls) {

            List<C2C1Info> data = new ArrayList<>();
            try {

                data = getListC2C1();

            } catch (Exception e) {

            }
            return data;
        }

        @Override
        protected void onPreExecute() {
            showpDialog();
        }

        protected void onPostExecute(List<C2C1Info> result) {
            agencyList = new ArrayList<>();
            agencyListTemp = new ArrayList<>();
            for (C2C1Info info : result) {
                agencyList.add(info);
                agencyListTemp.add(info);
            }

            mAdapter = new C2C1Adapter(agencyList);
            recyclerView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
            hidepDialog();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);
        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.find_action).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                handleSearch(newText);
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.refesh_action:
                makeRequest();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void handleSearch(String query) {
        agencyList.clear();

        for(C2C1Info info: agencyListTemp) {
            if (info.getCode().contains(query)){
                agencyList.add(info);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

}


text:
<!DOCTYPE html>

    <link rel="shortcut icon" href="#"/>
    <title>JobSpotter</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="src/main.css">
    <link rel="icon" type="image/png" href="/jsfavicon.png" sizes="96x96">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">


text:
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using CQRS.Light.Core;
using CQRS.Light.Contracts;
using CQRS.Light.Repository.MongoDB;
using DDD.Light.Realtor.API.Command.Realtor;
using DDD.Light.Realtor.REST.API.Bootstrap;
using StructureMap;
using System.Threading.Tasks;

namespace DDD.Light.Realtor.REST.API
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            SetUpIoC();

            EventStore.Instance.Configure(new MongoRepository<AggregateEvent>("mongodb://localhost", "DDD_Light_Realtor", "EventStore"),
                new JsonSerializationStrategy(), AggregateBus.Instance);
            EventBus.Instance.Configure(EventStore.Instance, new JsonSerializationStrategy(), false);

            AggregateCache.Instance.Configure(EventStore.Instance, DependencyResolution.ObjectFactory.Container.GetInstance);
            AggregateBus.Instance.Configure(EventBus.Instance, AggregateCache.Instance);

            InitApp(EventStore.Instance);
        }

        private static void InitApp(IEventStore eventStore)
        {
            HandlerSubscribtions.SubscribeAllHandlers(DependencyResolution.ObjectFactory.Container.GetInstance);
            CreateRealtorIfNoneExist(eventStore).ConfigureAwait(false);
        }

        private static void SetUpIoC()
        {
            var container = StructureMapConfig.ConfigureDependencies();
            GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
        }

        private static async Task CreateRealtorIfNoneExist(IEventStore eventStore)
        {
            var realtorId = Guid.Parse("10000000-0000-0000-0000-000000000000");
            if (await eventStore.GetByIdAsync(realtorId) == null)
                await CommandBus.Instance.DispatchAsync(new SetUpRealtor(realtorId));
        }
    }
}


text:
// ***********************************************************************************
// Created by zbw911
// 创建于:2013年01月30日 11:41
//
// 修改于:2013年01月30日 18:06
// 文件名:SimpleDbContextStorage.cs
//
// 如果有更好的建议或意见请邮件至zbw911#gmail.com
// ***********************************************************************************

namespace Dev.Data.ContextStorage
{
    using System.Collections.Generic;
    using System.Data.Entity;

    /// <summary>
    /// 使用 Dictionary 存储上下文
    /// </summary>
    public class SimpleDbContextStorage : IDbContextStorage
    {
        #region Fields

        private readonly Dictionary<string, DbContext> _storage = new Dictionary<string, DbContext>();

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///     Returns all the values of the internal dictionary of db contexts.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<DbContext> GetAllDbContexts()
        {
            return this._storage.Values;
        }

        /// <summary>
        ///     Returns the db context associated with the specified key or
        ///     null if the specified key is not found.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public DbContext GetDbContextForKey(string key)
        {
            DbContext context;
            if (!this._storage.TryGetValue(key, out context))
            {
                return null;
            }
            return context;
        }

        /// <summary>
        ///     Stores the db context into a dictionary using the specified key.
        ///     If an object context already exists by the specified key,
        ///     it gets overwritten by the new object context passed in.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="context">The object context.</param>
        public void SetDbContextForKey(string key, DbContext context)
        {
            this._storage.Add(key, context);
        }

        #endregion
    }
}


text:
angular.module('concertoPanel').filter('logical', [
    function () {
        return function (value) {
            return value == 1 ? Trans.TEST_VARS_PARAMS_LIST_FIELD_URL_YES : Trans.TEST_VARS_PARAMS_LIST_FIELD_URL_NO;
        };
    }
]);


text:
<?php

namespace Model;

use MongoConnection;

class Owner
{

	public static function find()
	{
		$collection = MongoConnection::instance()
			->collection('owners');

		return $collection->find(function ($query){
			/** @var \League\Monga\Query\Find $query */
			$query->orderBy('_id', 'asc');
		});
	}

	public static function findOne($username)
	{
		$collection = MongoConnection::instance()
			->collection('owners');

		$user = $collection->findOne(function($query) use ($username){
			/** @var \League\Monga\Query\Find $query */
			$query->where('_id', $username);
		});

		$petResult = MongoConnection::instance()
			->collection('pets')
			->find(function($query) use ($user){
				/** @var \League\Monga\Query\Find $query */
				$query->andWhereIn('_id', $user['pets']);
			});

		$pets = [];
		foreach ($petResult as $pet)
		{
			$petInfo = $pet;
			$petInfo['name_slug'] = \Inflector::friendly_title($pet['name']);
			$pets[] = $petInfo;
		}

		$user['pets'] = $pets;

		return $user;
	}

}


text:
import { ProjectConfiguration, Tree, getProjects } from '@nrwl/devkit';

function filterProjects(
  tree: Tree,
  filter: (projectConfiguration: ProjectConfiguration) => boolean,
  name?: string
): Map<string, ProjectConfiguration> {
  const projectConfigurations = getProjects(tree);
  const projects = new Map<string, ProjectConfiguration>();
  if (name) {
    const projectNames = name
      .split(',')
      .map((projectName) => projectName.trim())
      .filter(
        (projectName) => projectName && projectConfigurations.has(projectName)
      );
    projectNames.forEach((projectName) => {
      const projectConfiguration = projectConfigurations.get(projectName);
      if (projectConfiguration && filter(projectConfiguration)) {
        projects.set(projectName, projectConfiguration);
      }
    });
  } else {
    projectConfigurations.forEach((projectConfiguration, projectName) => {
      if (filter(projectConfiguration)) {
        projects.set(projectName, projectConfiguration);
      }
    });
  }
  return projects;
}

function projectHasTargetWithExecutor(
  projectConfiguration: ProjectConfiguration,
  executor: string
): boolean {
  return (
    !!projectConfiguration.targets &&
    Object.values(projectConfiguration.targets).some(
      (target) => target.executor === executor
    )
  );
}

export function getE2eProjects(
  tree: Tree,
  name?: string
): Map<string, ProjectConfiguration> {
  return filterProjects(
    tree,
    (projectConfiguration) =>
      projectHasTargetWithExecutor(
        projectConfiguration,
        '@nrwl/cypress:cypress'
      ),
    name
  );
}

export function getStorybookProjects(
  tree: Tree,
  name?: string
): Map<string, ProjectConfiguration> {
  return filterProjects(
    tree,
    (projectConfiguration) =>
      projectHasTargetWithExecutor(
        projectConfiguration,
        '@storybook/angular:build-storybook'
      ),
    name
  );
}

export function getStorybookProject(
  tree: Tree,
  options: Partial<{ project: string }>
) {
  if (!options.project) {
    throw new Error(`Project name not specified`);
  }

  const projects = getProjects(tree);
  if (!projects.has(options.project)) {
    throw new Error(`Unable to find project ${options.project}`);
  }
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  let projectConfig = projects.get(options.project)!;

  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  if (!('storybook' in projectConfig.targets!)) {
    options.project = `${options.project}-storybook`;
    if (!projects.has(options.project)) {
      throw new Error(`Unable to find project ${options.project}`);
    }
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    projectConfig = projects.get(options.project)!;

    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    if (!('storybook' in projectConfig.targets!)) {
      throw new Error(`Storybook is not configured for ${options.project}`);
    }
  }
  return projectConfig;
}

export function getProjectTypeBase(projectConfig: ProjectConfiguration) {
  return `${projectConfig.projectType == 'library' ? 'lib' : 'app'}`;
}


text:
export enum ALTER_MODE {
    ADD,
    EDIT,
    DELETE
}


text:
package org.apache.pulsar.common.policies.data;

import java.util.Map;
import org.apache.pulsar.client.api.ProducerAccessMode;

/**
 * Statistics about a publisher.
 */
public interface PublisherStats {

    ProducerAccessMode getAccessMode();

    /** Total rate of messages published by this publisher (msg/s). */
    double getMsgRateIn();

    /** Total throughput of messages published by this publisher (byte/s). */
    double getMsgThroughputIn();

    /** Average message size published by this publisher. */
    double getAverageMsgSize();

    /** The total rate of chunked messages published by this publisher. **/
    double getChunkedMessageRate();

    /** Id of this publisher. */
    long getProducerId();

    /** Whether partial producer is supported at client. */
    boolean isSupportsPartialProducer();

    /** Producer name. */
    String getProducerName();

    /** Address of this publisher. */
    String getAddress();

    /** Timestamp of connection. */
    String getConnectedSince();

    /** Client library version. */
    String getClientVersion();

    /** Metadata (key/value strings) associated with this publisher. */
    Map<String, String> getMetadata();
}


text:
package com.decaf.money

case object GetMarketDetails


text:
"{{tweet.text}}"

 on {{tweet.curDate | date:'MMM dd, yyyy'}} at {{tweet.curDate | date:'h:mm a'}}


text:
import MySQLdb, time, logging, requests, json, random, hashlib
import jieba.posseg as pseg
from werkzeug.contrib.cache import MemcachedCache
from config import Credentials, AdvancedSettings

class Word:
    @staticmethod
    def remove_symbols(string):
        for i in AdvancedSettings.remove_words_list:
            string = string.replace(i, u'')
        return string

    @staticmethod
    def gen_trunk(string):
        words = pseg.cut(string)
        trunk = map(lambda y: y.word, filter(lambda x: x.flag in AdvancedSettings.trunk_list, words))
        return trunk

class Memcache:
    WAIT_ASK = 1
    WAIT_ANSWER = 2

    def __init__(self):
        self.cache = MemcachedCache(['127.0.0.1:11211'])

    def get(self, key):
        ret = self.cache.get(key)
        try:
            ret = ret.decode('utf-8')
        except:
            pass
        return ret

    def set(self, key, value):
        try:
            value = value.encode('utf-8')
        except:
            pass
        return self.cache.set(key, value, timeout=600)

    def delete(self, key):
        return self.cache.delete(key)

    def check_history(self, qid, gid=0):
        r = self.get(u'H' + str(qid) + u'G' + str(gid))
        if r is None:
            return r, r
        if r == self.WAIT_ANSWER:
            return self.WAIT_ANSWER, self.get(u'A' + str(qid) + u'G' + str(gid))
        if r == self.WAIT_ASK:
            return self.WAIT_ASK, None
        return None

    def set_before_ask(self, qid, gid=0):
        self.set(u'H' + str(qid) + u'G' + str(gid), self.WAIT_ASK)

    def set_before_answer(self, qid, ask, gid=0):
        self.set(u'A' + str(qid) + u'G' + str(gid), ask)
        self.set(u'H' + str(qid) + u'G' + str(gid), self.WAIT_ANSWER)

    def clear_state(self, qid, gid=0):
        self.delete(u'A' + str(qid) + u'G' + str(gid))
        self.delete(u'H' + str(qid) + u'G' + str(gid))

    def last_warn_time(self, qid):
        self.set(u'W'+str(qid), time.time())

    def check_last_chat_same(self, qid, msg):
        if self.get(u'LC'+str(qid)) and self.get(u'LC'+str(qid)) == msg:
            return self.last_chat_count(qid, add=True)
        self.set(u'LC'+str(qid), msg)
        self.set(u'LCC'+str(qid), 1)
        return True

    def last_chat_count(self, qid, add=False):
        lcc = self.get(u'LCC'+str(qid))
        if not lcc:
            self.set(u'LCC'+str(qid), 1)
            return True
        if add and lcc <= AdvancedSettings.same_response_limit:
            self.cache.inc(u'LCC'+str(qid))
            lcc += 1
        return lcc < AdvancedSettings.same_response_limit

    def check_block_user(self, qid):
        x = self.get(u'BU'+str(qid))
        if x is not None:
            return x
        db = MyDB()
        is_blocked = db.check_blocked(qid, 'user')
        logging.info("is_blocked")
        logging.info(is_blocked)
        self.set(u'BU'+str(qid), is_blocked)
        return is_blocked

    def check_block_group(self, gid):
        x = self.get(u'BG'+str(gid))
        if x is not None:
            return x
        db = MyDB()
        is_blocked = db.check_blocked(gid, 'group')
        self.set(u'BG'+str(gid), is_blocked)
        return is_blocked

    def check_disable_group(self, gid):
        x = self.get(u'BD'+str(gid))
        if x is not None:
            return x
        db = MyDB()
        is_disabled = db.check_disabled(gid)
        self.set(u'BD'+str(gid), is_disabled)
        return is_disabled

class MyDB:
    def __init__(self):
        self.db = MySQLdb.connect(host=Credentials.database[0],
                                  user=Credentials.database_account[0],
                                  passwd=Credentials.database_account[1],
                                  db=Credentials.database[1],
                                  charset='utf8'
                                  )
        self.db.autocommit(True)

    def __del__(self):
        self.db.close()

    def execute(self, sql, params=tuple()):
        cursor = self.db.cursor()
        try:
            cursor.execute(sql, params)
        except:
            pass
        return cursor

    def query_exact_question(self, question):
        # question = Word.remove_symbols(question)
        sql = "SELECT * FROM `chat` WHERE `ask`=%s AND `deleted`!=1 ORDER BY RAND() LIMIT 1"
        return self.execute(sql, (question,)).fetchone()

    def query_admin(self, question):
        sql = "SELECT * FROM `chat` WHERE `ask` LIKE %%s% AND `deleted`!=1 LIMIT 30"
        return self.execute(sql, (question,)).fetchone()

    def query_question(self, question):
        question = Word.remove_symbols(question)
        data = self.query_exact_question(question)
        if data is not None:
            return data
        query_string = u'%'.join(Word.gen_trunk(question))
        sql = "SELECT * FROM `chat` WHERE `ask` LIKE %s AND `deleted`!=1 ORDER BY RAND() LIMIT 1"
        return self.execute(sql, (question,)).fetchone()

    def insert_chat(self, ask, answer, committer, gid=0):
        ask = Word.remove_symbols(ask)
        sql = "INSERT INTO `chat`(`ask`,`answer`,`committer`,`gid`,`time`) VALUES(%s,%s,%s,%s,NOW())"
        self.execute(sql, (ask, answer, committer, gid))

    def get_user_info(self, qid):
        sql = "SELECT * FROM `user` WHERE `uid`=%s"
        return self.execute(sql, (qid,)).fetchone()

    def get_group_info(self, gid):
        sql = "SELECT * FROM `group` WHERE `gid`=%s"
        return self.execute(sql, (gid,)).fetchone()

    def block_user(self, qid, unblock=False):
        sql = "UPDATE `user` SET `blocked`=1 WHERE `uid`=%s"
        if unblock:
            sql = "UPDATE `user` SET `blocked`=0 WHERE `uid`=%s"
        self.execute(sql, (qid,))
        mem = Memcache()
        mem.delete(u'BU'+str(qid))

    def block_group(self, gid, unblock=False):
        sql = "UPDATE `group` SET `blocked`=1 WHERE `gid`=%s"
        if unblock:
            sql = "UPDATE `group` SET `blocked`=1 WHERE `gid`=%s"
        self.execute(sql, (gid,))
        mem = Memcache()
        mem.delete(u'BG'+str(gid))

    def disable_group(self, gid, disable=False):
        sql = "UPDATE `group` SET `disabled`=0 WHERE `gid`=%s"
        if disable:
            sql = "UPDATE `group` SET `disabled`=1 WHERE `gid`=%s"
        self.execute(sql, (gid,))
        mem = Memcache()
        mem.delete(u'BD'+str(gid))

    def top_user(self):
        sql = "SELECT * FROM `user` ORDER BY `coin` DESC LIMIT 15"
        return self.execute(sql).fetchall()

    def delete_talk(self, qid, content, is_super=False):
        if not is_super:
            sql = "UPDATE `chat` SET `deleted`=1 WHERE `uid`=%s AND `ask`=%s"
            self.execute(sql, (qid, content))
        else:
            sql = "UPDATE `chat` SET `deleted`=1 WHERE `ask`=%s"
            self.execute(sql, (content,))

    def init_user(self, qid):
        sql = "INSERT INTO `user`(`uid`) VALUES(%s)"
        self.execute(sql, (qid,))

    def init_group(self, gid):
        sql = "INSERT INTO `group`(`gid`) VALUES(%s)"
        self.execute(sql, (gid,))

    def check_blocked(self, xid, type='user'):
        if type == 'user':
            info = self.get_user_info(xid)
            if not info:
                self.init_user(xid)
                return True
            if info[2] and info[2] == 1:
                return False
            return True
        ginfo = self.get_group_info(xid)
        if not ginfo:
            self.init_group(xid)
            return True
        if ginfo[2] and ginfo[2] == 1:
            return False
        return True

    def check_disabled(self, gid):
        ginfo = self.get_group_info(gid)
        if not ginfo:
            self.init_group(gid)
            return True
        if ginfo[1] and ginfo[1] == 1:
            return False
        return True

    def mod_coin(self, qid, x):
        x = int(x)
        if x < 0:
            x = str(x)
        else:
            x = '+' + str(x)
        sql = "UPDATE `user` SET `coin`=`coin`+" + x + " WHERE `uid`=%s"
        cursor = self.db.cursor()
        self.execute(sql, (qid,))

class UserMod:
    IS_ADMIN = 3
    NOT_ADMIN = 0
    NO_GROUP_INFO = 1
    NO_USER_INFO = 2

    def check_group_admin(self, gid, qid):
        url = "%s/openqq/get_group_info" % Credentials.comm_url
        groups = json.loads(requests.get(url).content)
        gid, qid = int(gid), int(qid)
        group = filter(lambda g: int(g[u'gnumber']) == gid, groups)
        if group:
            group = group[0]
            admins = map(lambda member: int(member[u'qq']),
                         filter(lambda x: x[u'role'] == u'admin' or x[u'role'] == u'owner', group[u'member'])
                         )
            if qid in admins:
                return self.IS_ADMIN
            me = filter(lambda x: int(x[u'qq']) == qid, group[u'member'])
            if me:
                return self.NOT_ADMIN
            return self.NO_USER_INFO
        return self.NO_GROUP_INFO

class TuringBot:
    def proc_message(self):
        content = json.loads(self.content)
        if content[u'code'] == 100000:
            # Text
            return content[u'text']
        if AdvancedSettings.turing_robot_only_text:
            return u''
        if content[u'code'] == 200000:
            # Link
            return content[u'text'] + u'\n' + content[u'url']
        if content[u'code'] == 302000:
            # News
            return content[u'text'] + u'\n' + u'\n'.join(map(lambda x: x[u'article'], content[u'list']))
        if content[u'code'] == 308000:
            # Cookbook
            return content[u'text'] + u'\n' + u'\n'.join(map(lambda x: x[u'info'], content[u'list']))
        return u''

    def __init__(self, info, userid):
        self.content = requests.post(AdvancedSettings.turing_robot_url,
                                     {'key': random.choice(AdvancedSettings.turing_robot_api),
                                      'info': info.encode('utf-8'),
                                      'userid': hashlib.md5(AdvancedSettings.turing_robot_userid_salt + str(userid)).hexdigest()
                                      }).content


text:
import {RouterTestingModule} from '@angular/router/testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {StoreModule} from '@ngrx/store';
import {EffectsModule} from '@ngrx/effects';
import {MetamodelService} from '../metamodel.service';
import {MockSharedAppService} from '../../../tests/service/app.service.mock';
import {ParserService} from '../../shared/service/parser.service';
import {LoggerService} from '../../../shared/service/logger.service';
import {StreamsModule} from '../../../streams/streams.module';
import {NotificationService} from '../../../shared/service/notification.service';
import {StreamFloCreateComponent} from './create.component';
import {SharedModule} from '../../../shared/shared.module';
import {StreamService} from '../../../shared/api/stream.service';
import {MockStreamsService} from '../../../tests/service/stream.service.mock';
import {NotificationServiceMock} from '../../../tests/service/notification.service.mock';

/**
 * Test {@link StreamCreateComponent}.
 *
 * @author Glenn Renfro
 */
describe('StreamCreateComponent', () => {
  let component: StreamFloCreateComponent;
  let fixture: ComponentFixture<StreamFloCreateComponent>;
  const streamsService = new MockStreamsService();
  const metamodelService = new MetamodelService(new MockSharedAppService());
  const parserService = new ParserService();
  const loggerService = new LoggerService();
  const notificationService = new NotificationServiceMock();

  // const commonTestParams = { id: '1' };

  beforeEach(async () => {
    // activeRoute = new MockActivatedRoute();

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([]),
        BrowserAnimationsModule,
        SharedModule,
        StreamsModule,
        StoreModule.forRoot({}),
        EffectsModule.forRoot([])
      ],
      providers: [
        {provide: StreamService, useValue: streamsService},
        {provide: MetamodelService, useValue: metamodelService},
        {provide: NotificationService, useValue: notificationService},
        {provide: ParserService, useValue: parserService},
        {provide: LoggerService, useValue: loggerService}
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StreamFloCreateComponent);
    component = fixture.componentInstance;
  });

  it('should be created', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  xit('disable stream creation for empty streams', () => {
    fixture.detectChanges();
    expect(component.dsl).toBeUndefined();
    expect(component.isCreateStreamsDisabled).toBeTruthy();
  });

  it('enable stream creation for valid stream', done => {
    fixture.detectChanges();
    expect(component.isCreateStreamsDisabled).toBeTruthy();
    component.dsl = 'http | ftp';
    fixture.detectChanges();
    // Validation is performed after a delay, hence the wait
    setTimeout(() => {
      expect(component.dsl).toEqual('http | ftp');
      expect(component.parseErrors).toEqual([]);
      const allMarkers = [];
      Array.from(component.validationMarkers.values()).forEach(markers => allMarkers.push(...markers));
      expect(allMarkers.length).toEqual(0);
      expect(component.isCreateStreamsDisabled).toBeFalsy();
      done();
    }, 1000);
  });

  it('disable stream creation for parse error', done => {
    fixture.detectChanges();
    expect(component.isCreateStreamsDisabled).toBeTruthy();
    component.dsl = 'http -ghdfv | ftp';
    fixture.detectChanges();
    // Validation is performed after a delay, hence the wait
    setTimeout(() => {
      expect(component.dsl).toEqual('http -ghdfv | ftp');
      expect(component.parseErrors.length).toEqual(1);
      const allMarkers = [];
      Array.from(component.validationMarkers.values()).forEach(markers => allMarkers.push(...markers));
      expect(allMarkers.length).toEqual(0);
      expect(component.isCreateStreamsDisabled).toBeTruthy();
      done();
    }, 1000);
  });

  it('disable stream creation for invalid stream (space)', done => {
    fixture.detectChanges();
    expect(component.isCreateStreamsDisabled).toBeTruthy();
    component.dsl = ' ';
    fixture.detectChanges();
    // Validation is performed after a delay, hence the wait
    setTimeout(() => {
      expect(component.dsl).toEqual(' ');
      expect(component.parseErrors.length).toEqual(0);
      const allMarkers = [];
      Array.from(component.validationMarkers.values()).forEach(markers => allMarkers.push(...markers));
      expect(allMarkers.length).toEqual(0);
      expect(component.isCreateStreamsDisabled).toBeTruthy();
      done();
    }, 1000);
  });

  it('disable stream creation for graph validation error marker', done => {
    fixture.detectChanges();
    expect(component.isCreateStreamsDisabled).toBeTruthy();
    component.dsl = 'http';
    fixture.detectChanges();
    // Validation is performed after a delay, hence the wait
    // Should trigger source no connected to anything kind of validation error marker
    setTimeout(() => {
      expect(component.dsl).toEqual('http');
      expect(component.parseErrors.length).toEqual(0);
      const allMarkers = [];
      Array.from(component.validationMarkers.values()).forEach(markers => allMarkers.push(...markers));
      expect(allMarkers.length).toEqual(1);
      expect(component.isCreateStreamsDisabled).toBeTruthy();
      done();
    }, 1000);
  });
});


text:
FINGER_JOINT_VALUE=20.0
TIP_JOINT_VALUE=40.0

rostopic pub -1 /kinova_kg3/jaco_joint_finger_1_position_controller/command std_msgs/Float64 "data: $FINGER_JOINT_VALUE"
rostopic pub -1 /kinova_kg3/jaco_joint_finger_2_position_controller/command std_msgs/Float64 "data: $FINGER_JOINT_VALUE"
rostopic pub -1 /kinova_kg3/jaco_joint_finger_3_position_controller/command std_msgs/Float64 "data: $FINGER_JOINT_VALUE"

rostopic pub -1 /kinova_kg3/jaco_joint_finger_tip_1_position_controller/command std_msgs/Float64 "data: $TIP_JOINT_VALUE"
rostopic pub -1 /kinova_kg3/jaco_joint_finger_tip_2_position_controller/command std_msgs/Float64 "data: $TIP_JOINT_VALUE"
rostopic pub -1 /kinova_kg3/jaco_joint_finger_tip_3_position_controller/command std_msgs/Float64 "data: $TIP_JOINT_VALUE"


text:
*NOTE: This page is now obsolete (for reference only!)*

## Download Nightcode

Nightcode is an integrated development environment (IDE) for
creating Clojure programs. You can download it from:

https://sekao.net/nightcode/

## Setup Nightcode on Windows

In your brower can you can right click on the nightcode jar file
and select "open containing folder"

![Open containing folder](img/new/nc2.png)

Once you are viewing the Downloads folder in Explorer, right
click on the jar file and select **Send to | Desktop (create shortcut)**

![Create Shortcut](img/new/nc3.png)

On Windows you can double click on jar files to launch them..
So double click on the nightcode jar:

![Launch nightcode](img/new/nc4.png)

Finally you can open the **clojure-getting-started** project we worked on
in Nightcode:

![Open clojure-getting-started](img/new/nc5.png)

## Setup Nightcode on Mac

On the Nightcode homepage select the download for Mac. Open the Downloads
directory in a Finder window and double click the Nightcode-2.1.5.dmg file.
Drag the Nightcode app into the Applications directory.

![Mac Install](img/new/nc_mac0.png)

Nightcode can now be launched from Finder, Launchpad, or Spotlight. Note
that you will see the following prompt the first time Nightcode is opened,
click **Open**.

![Open Prompt](img/new/nc_mac1.png)

Now you can open the **clojure-getting-started** repo in Nightcode (see above).

## Setup Nightcode on Linux

The setup for Linux is the same as for Mac!

You _might_ encounter a problem where Nightcode seems to
crash after startup... If that happens you probably need
to be running a compositing Window Manager. You can add this
feature to your current environment by adding this package:

````
# apt-get install xcompmgr
````

And starting the compositing manager before Nightcode:

````
clojurista@mylaptop $ xcompmgr &
clojurista@mylaptop $ nightcode
````

Now you can open the **clojure-getting-started** repo in Nightcode (see above).


text:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var multipart = require('connect-multiparty');
var fs = require('fs');

var upload = express();

upload.use(bodyParser({
    keepExtensions: true,
    uploadDir: path.join(__dirname,'/files')
}));
upload.get('/crossdomain.xml', function(req, res){
    res.sendfile('crossdomain.xml');
});

var count = 0;
upload.all('/',multipart(),function(req,res){
    res.header('Access-Control-Allow-Origin','*');

    if(req.method.toLowerCase() == 'options'){
        return res.send('ok');
    }

    var file = req.files.key;
    var tmp_path = file.path;
    var target_path = './res/' + file.name;

    count++;
    // if(count%3 == 0){
    //     return res.send(200,{
    //         code: 500,
    //         message: "something wrong happened"
    //     });
    // }else if(count%3 == 1){
    //     return res.send(500,"oops");
    // }
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) return res.send(500,err);
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) return res.send(500,err);
            setTimeout(function(){
                res.send({
                    code: 200,
                    path: "/res/" + file.name,
                    size: file.size
                });
            });
        });
    });
});

upload.listen(1339);

console.log("upload server started at 1339");

var web = express();
web.use(express.static(__dirname))
web.listen(1234);
console.log("upload server started at 1234");


text:
<?php
namespace Elgg\Cache;

/**
 * Least Recently Used Cache
 *
 * A fixed sized cache that removes the element used last when it reaches its
 * size limit.
 *
 * Based on https://github.com/cash/LRUCache
 *
 * @access private
 *
 * @package    Elgg.Core
 * @subpackage Cache
 */
class LRUCache implements \ArrayAccess {
	/** @var int */
	protected $maximumSize;

	/**
	 * The front of the array contains the LRU element
	 *
	 * @var array
	 */
	protected $data = array();

	/**
	 * Create a LRU Cache
	 *
	 * @param int $size The size of the cache
	 * @throws \InvalidArgumentException
	 */
	public function __construct($size) {
		if (!is_int($size) || $size <= 0) {
			throw new \InvalidArgumentException();
		}
		$this->maximumSize = $size;
	}

	/**
	 * Get the value cached with this key
	 *
	 * @param int|string $key     The key. Strings that are ints are cast to ints.
	 * @param mixed      $default The value to be returned if key not found. (Optional)
	 * @return mixed
	 */
	public function get($key, $default = null) {
		if (isset($this->data[$key])) {
			$this->recordAccess($key);
			return $this->data[$key];
		} else {
			return $default;
		}
	}

	/**
	 * Add something to the cache
	 *
	 * @param int|string $key   The key. Strings that are ints are cast to ints.
	 * @param mixed      $value The value to cache
	 * @return void
	 */
	public function set($key, $value) {
		if (isset($this->data[$key])) {
			$this->data[$key] = $value;
			$this->recordAccess($key);
		} else {
			$this->data[$key] = $value;
			if ($this->size() > $this->maximumSize) {
				// remove least recently used element (front of array)
				reset($this->data);
				unset($this->data[key($this->data)]);
			}
		}
	}

	/**
	 * Get the number of elements in the cache
	 *
	 * @return int
	 */
	public function size() {
		return count($this->data);
	}

	/**
	 * Does the cache contain an element with this key
	 *
	 * @param int|string $key The key
	 * @return boolean
	 */
	public function containsKey($key) {
		return isset($this->data[$key]);
	}

	/**
	 * Remove the element with this key.
	 *
	 * @param int|string $key The key
	 * @return mixed Value or null if not set
	 */
	public function remove($key) {
		if (isset($this->data[$key])) {
			$value = $this->data[$key];
			unset($this->data[$key]);
			return $value;
		} else {
			return null;
		}
	}

	/**
	 * Clear the cache
	 *
	 * @return void
	 */
	public function clear() {
		$this->data = array();
	}

	/**
	 * Moves the element from current position to end of array
	 *
	 * @param int|string $key The key
	 * @return void
	 */
	protected function recordAccess($key) {
		$value = $this->data[$key];
		unset($this->data[$key]);
		$this->data[$key] = $value;
	}

	/**
	 * Assigns a value for the specified key
	 *
	 * @see \ArrayAccess::offsetSet()
	 *
	 * @param int|string $key   The key to assign the value to.
	 * @param mixed      $value The value to set.
	 * @return void
	 */
	public function offsetSet($key, $value) {
		$this->set($key, $value);
	}

	/**
	 * Get the value for specified key
	 *
	 * @see \ArrayAccess::offsetGet()
	 *
	 * @param int|string $key The key to retrieve.
	 * @return mixed
	 */
	public function offsetGet($key) {
		return $this->get($key);
	}

	/**
	 * Unsets a key.
	 *
	 * @see \ArrayAccess::offsetUnset()
	 *
	 * @param int|string $key The key to unset.
	 * @return void
	 */
	public function offsetUnset($key) {
		$this->remove($key);
	}

	/**
	 * Does key exist?
	 *
	 * @see \ArrayAccess::offsetExists()
	 *
	 * @param int|string $key A key to check for.
	 * @return boolean
	 */
	public function offsetExists($key) {
		return $this->containsKey($key);
	}
}


text:
"""Everything and the kitchen sink."""
from .color import Color as Base
from .spaces.rec2100pq import Rec2100PQ
from .spaces.jzazbz import Jzazbz
from .spaces.jzczhz import JzCzhz
from .spaces.ictcp import ICtCp
from .spaces.din99o import DIN99o
from .spaces.lch99o import LCh99o
from .spaces.luv import Luv
from .spaces.lchuv import LChuv
from .spaces.hsluv import HSLuv
from .spaces.hpluv import HPLuv
from .spaces.okhsl import Okhsl
from .spaces.okhsv import Okhsv
from .spaces.hsi import HSI
from .spaces.ipt import IPT
from .spaces.igpgtg import IgPgTg
from .spaces.cmy import CMY
from .spaces.cmyk import CMYK
from .spaces.xyy import xyY
from .spaces.hunter_lab import HunterLab
from .spaces.prismatic import Prismatic
from .spaces.rlab import RLAB
from .spaces.orgb import oRGB
from .spaces.aces2065_1 import ACES20651
from .spaces.acescg import ACEScg
from .spaces.acescc import ACEScc
from .spaces.acescct import ACEScct
from .distance.delta_e_itp import DEITP
from .distance.delta_e_99o import DE99o
from .distance.delta_e_z import DEZ
from .interpolate.catmull_rom import CatmullRom
from .cat import VonKries, XYZScaling, CAT02, CMCCAT97, Sharp, CMCCAT2000, CAT16
from .color import ColorMatch
from .interpolate import stop, hint
from .algebra import NaN

__all__ = ('ColorAll', 'ColorMatch', 'stop', 'hint', 'NaN')

class ColorAll(Base):
    """Color with all plugins."""

ColorAll.register(
    [
        # Spaces
        Rec2100PQ(),
        Jzazbz(),
        JzCzhz(),
        ICtCp(),
        DIN99o(),
        LCh99o(),
        Luv(),
        LChuv(),
        Okhsl(),
        Okhsv(),
        HSLuv(),
        HPLuv(),
        HSI(),
        IPT(),
        IgPgTg(),
        CMY(),
        CMYK(),
        xyY(),
        HunterLab(),
        Prismatic(),
        RLAB(),
        oRGB(),
        ACES20651(),
        ACEScg(),
        ACEScc(),
        ACEScct(),

        # Delta E
        DEITP(),
        DE99o(),
        DEZ(),

        # CAT
        VonKries(),
        XYZScaling(),
        CAT02(),
        CMCCAT97(),
        Sharp(),
        CMCCAT2000(),
        CAT16(),

        # Interpolation
        CatmullRom()
    ]
)


text:
import { stripIndent } from 'common-tags';
import * as Debug from 'debug';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';
import * as yargs from 'yargs';
import {
  EnvironmentDictionary,
  getScriptToExecute,
  setEnvironmentVariables,
} from './utils';

export interface CliOptions extends yargs.Arguments {
  force: boolean;
  env: string;
  verbose: boolean;
  encoding: string;
  exec: string;
  script: string;
  newArguments: string[];
}

export type CliArgs = {
  program: CliOptions;
  script: string | undefined;
};

export type Cli =
  | { isRepl: true; node: boolean }
  | { isRepl: false; error?: Error; script?: string };

const debug = Debug('node-env-run');
const cwd = process.cwd();

const usageDescription = stripIndent`
  Runs the given script with set environment variables.
  * If no script is passed it will run the REPL instead.
  * If '.' is passed it will read the package.json and execute the 'main' file.

  Pass additional arguments to the script after the "--"
`;

/**
 * Parses a list of arguments and turns them into an object using Commander
 * @param  {string[]} argv Array of arguments like process.argv
 * @returns {CliArgs} The parsed configuration
 */
export function parseArgs(argv: string[]): CliArgs {
  const result = yargs
    .usage('$0 [script]', usageDescription, (yargs) => {
      yargs.positional('script', {
        describe: 'the file that should be executed',
        type: 'string',
      });
      yargs.example('$0 --exec "python"', 'Runs the Python REPL instead');
      yargs.example(
        '$0 server.js --exec "nodemon"',
        'Runs "nodemon server.js"'
      );
      yargs.example(
        '$0 someScript.js -- --inspect',
        'Run script with --inspect'
      );
      return yargs;
    })
    .option('force', {
      alias: 'f',
      demandOption: false,
      describe:
        'temporarily overrides existing env variables with the ones in the .env file',
    })
    .option('env', {
      alias: 'E',
      demandOption: false,
      describe:
        'location of .env file relative from the current working directory',
      default: '.env',
      type: 'string',
    })
    .option('verbose', {
      demandOption: false,
      describe: 'enable verbose logging',
      type: 'boolean',
    })
    .option('encoding', {
      demandOption: false,
      describe: 'encoding of the .env file',
      default: 'utf8',
      type: 'string',
    })
    .option('exec', {
      alias: 'e',
      demandOption: false,
      describe: 'the command to execute the script with',
      default: 'node',
    })
    .showHelpOnFail(true)
    .help('help')
    .strict()
    .version()
    .parse(argv.slice(2)) as CliOptions;

  const script: string | undefined = result.script;
  result.newArguments = result._;

  debug('Yargs Result %o', result);

  return { program: result, script };
}

/**
 * Reads .env file, sets the environment variables and dtermines the script to execute
 * @param  {CliArgs} args The arguments as parsed by parseArgs
 * @returns {Cli} An object specifying if it should execute the REPL or execute a script
 */
export function init(args: CliArgs): Cli {
  const { program, script } = args;
  const envFilePath = path.resolve(cwd, program.env);
  if (!fs.existsSync(envFilePath)) {
    const error = new Error(
      `Could not find the .env file under: "${envFilePath}"`
    );
    return { isRepl: false, error };
  }

  debug('Reading .env file');
  const envContent = fs.readFileSync(
    path.resolve(cwd, program.env),
    program.encoding
  );
  const envValues: EnvironmentDictionary = dotenv.parse(envContent);

  setEnvironmentVariables(envValues, program.force);

  if (!script || script === 'REPL') {
    const node = args.program.exec === undefined;
    return { isRepl: true, node };
  }

  const scriptToExecute = getScriptToExecute(script, cwd);
  if (scriptToExecute === null || !fs.existsSync(scriptToExecute)) {
    const error = new Error('Failed to determine script to execute');
    return { isRepl: false, error };
  }

  return { isRepl: false, script: scriptToExecute };
}


text:
namespace IECorePython
{
#ifdef IECORE_WITH_DEEPEXR
IECOREPYTHON_API void bindEXRDeepImageReader();
#endif
}

#endif // IECOREPYTHON_EXRDEEPIMAGEREADER_BINDING


text:
package org.rabix.bindings.draft3.processor.callback;

import java.util.Map;
import java.util.Set;

import org.rabix.bindings.draft3.bean.Draft3Job;
import org.rabix.bindings.draft3.processor.Draft3PortProcessor;
import org.rabix.bindings.draft3.processor.Draft3PortProcessorException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.bindings.model.FileValue;
import org.rabix.bindings.transformer.FileTransformer;

public class Draft3PortProcessorHelper {

  private final Draft3Job draft3Job;
  private final Draft3PortProcessor portProcessor;

  public Draft3PortProcessorHelper(Draft3Job draft3Job) {
    this.draft3Job = draft3Job;
    this.portProcessor = new Draft3PortProcessor(draft3Job);
  }

  public Set<FileValue> getInputFiles(Map<String, Object> inputs, FilePathMapper fileMapper, Map<String, Object> config) throws Draft3PortProcessorException {
    if (fileMapper != null) {
      Draft3FilePathMapProcessorCallback fileMapperCallback = new Draft3FilePathMapProcessorCallback(fileMapper, config);
      inputs = portProcessor.processInputs(inputs, fileMapperCallback);
    }

    Draft3FileValueProcessorCallback callback = new Draft3FileValueProcessorCallback(draft3Job, null, true);
    try {
      portProcessor.processInputs(inputs, callback);
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to get input files.", e);
    }
    return callback.getFileValues();
  }

  public Set<FileValue> getOutputFiles(Map<String, Object> outputs, Set<String> visiblePorts) throws Draft3PortProcessorException {
    Draft3FileValueProcessorCallback callback = new Draft3FileValueProcessorCallback(draft3Job, visiblePorts, false);
    try {
      portProcessor.processOutputs(outputs, callback);
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to get output files.", e);
    }
    return callback.getFileValues();
  }

  public Map<String, Object> updateInputFiles(Map<String, Object> inputs, FileTransformer fileTransformer) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3FileValueUpdateProcessorCallback(fileTransformer));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> updateOutputFiles(Map<String, Object> outputs, FileTransformer fileTransformer) throws Draft3PortProcessorException {
    try {
      return portProcessor.processOutputs(outputs, new Draft3FileValueUpdateProcessorCallback(fileTransformer));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> setFileSize(Map<String, Object> inputs) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3FileSizeProcessorCallback());
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> loadInputContents(Map<String, Object> inputs) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3LoadContentsPortProcessorCallback());
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to load input contents.", e);
    }
  }

}


text:
define(['angular','ops-mgr/service-health/module-name'], function (angular,moduleName) {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {
                cardTitle: "@",
                refreshIntervalTime:"@"
            },
            controllerAs: 'vm',
            scope: true,
            templateUrl: 'js/ops-mgr/service-health/service-health-template.html',
            controller: "ServiceHealthController",
            link: function ($scope, element, attrs, controller) {

            }
        };
    }

    var controller = function ($scope,$http, $filter, $interval, $timeout, $q,ServicesStatusData, TableOptionsService, PaginationDataService, AlertsService, StateService) {
        var self = this;
        this.pageName = 'service-health';
        //Page State
        this.loading = true;
        this.showProgress = true;

        this.services = [];
        this.allServices = [];
        this.totalServices = 0;

        $scope.$watch(function(){
            return self.filter;
        },function(newVal){
            if(newVal && newVal != '') {
           //     self.services = $filter('filter')(self.allServices, newVal);
                self.totalServices = self.services.length;
            }
            else {
            //    self.services = self.allServices;
            }
        })

        //Pagination and view Type (list or table)
        this.paginationData = PaginationDataService.paginationData(this.pageName);
        PaginationDataService.setRowsPerPageOptions(this.pageName,['5','10','20','50','All']);
        this.viewType = PaginationDataService.viewType(this.pageName);
        this.currentPage =PaginationDataService.currentPage(self.pageName)||1;
        this.filter = PaginationDataService.filter(self.pageName);
        this.sortOptions = loadSortOptions();

        //Load the data
        loadData();

        //Refresh Intervals
        this.setRefreshInterval = setRefreshInterval;
        this.clearRefreshInterval = clearRefreshInterval;

        setRefreshInterval();

        this.paginationId = function(){
            return PaginationDataService.paginationId(self.pageName);
        }

        $scope.$watch(function(){
            return self.viewType;
        },function(newVal) {
            self.onViewTypeChange(newVal);
        })

        this.onViewTypeChange = function(viewType) {
            PaginationDataService.viewType(this.pageName, self.viewType);
        }

        //Tab Functions

        this.onOrderChange = function (order) {
            PaginationDataService.sort(self.pageName,order);
            TableOptionsService.setSortOption(self.pageName,order);
         //   return loadJobs(true).promise;
            //return self.deferred.promise;
        };

        this.onPaginationChange = function (page, limit) {
            PaginationDataService.currentPage(self.pageName,null,page);
            self.currentPage = page;
           // return loadJobs(true).promise;
        };

        //Sort Functions
        /**
         * Build the possible Sorting Options
         * @returns {*[]}
         */
        function loadSortOptions() {
            var options = {'Service Name':'serviceName','Components':'componentsCount','Alerts':'alertsCount','Update Date':'latestAlertTimestamp'};

            var sortOptions = TableOptionsService.newSortOptions(self.pageName,options,'serviceName','asc');
            TableOptionsService.initializeSortOption(self.pageName);
            return sortOptions;

        }

        /**
         * Called when a user Clicks on a table Option
         * @param option
         */
        this.selectedTableOption = function(option) {
            var sortString = TableOptionsService.toSortString(option);
            PaginationDataService.sort(self.pageName,sortString);
            var updatedOption = TableOptionsService.toggleSort(self.pageName,option);
            TableOptionsService.setSortOption(self.pageName,sortString);
        }

        //Load Jobs

        function loadData() {
                var successFn = function (data) {
                    self.services = data;
                    self.totalServices = self.services.length;
                    self.allServices = data;
                    self.loading == false;
                    self.showProgress = false;
                }
                var errorFn = function (err) {
                    console.log('error', err);
                }
                var finallyFn = function () {

                }
                //Only Refresh if the modal dialog does not have any open alerts
            ServicesStatusData.fetchServiceStatus(successFn,errorFn);

        }

        this.serviceDetails = function(event, service){
            StateService.OpsManager().ServiceStatus().navigateToServiceDetails(service.serviceName);
        }

        function clearRefreshInterval() {
            if (self.refreshInterval != null) {
                $interval.cancel(self.refreshInterval);
                self.refreshInterval = null;
            }
        }

        function setRefreshInterval() {
            self.clearRefreshInterval();
            if (self.refreshIntervalTime) {
                self.refreshInterval = $interval(loadData, self.refreshIntervalTime);

            }
        }

        $scope.$on('$destroy', function(){
            clearRefreshInterval();
        });

    };

    angular.module(moduleName).controller('ServiceHealthController', ["$scope","$http","$filter","$interval","$timeout","$q","ServicesStatusData","TableOptionsService","PaginationDataService","AlertsService","StateService",controller]);

    angular.module(moduleName)
        .directive('tbaServiceHealth', directive);

});


text:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.references :number
      t.references :letter

      t.timestamps
    end
  end
end


text:
class ShelfGuestSessionBrowserTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(ash::switches::kGuestSession);
    command_line->AppendSwitch(::switches::kIncognito);
    command_line->AppendSwitchASCII(ash::switches::kLoginProfile, "hash");
    command_line->AppendSwitchASCII(
        ash::switches::kLoginUser,
        user_manager::GuestAccountId().GetUserEmail());
  }
};

// Tests that in guest session, shelf alignment could be initialized to bottom
// aligned, instead of bottom locked (crbug.com/699661).
IN_PROC_BROWSER_TEST_F(ShelfGuestSessionBrowserTest, ShelfAlignment) {
  // Check the alignment pref for the primary display.
  ash::ShelfAlignment alignment = ash::GetShelfAlignmentPref(
      browser()->profile()->GetPrefs(),
      display::Screen::GetScreen()->GetPrimaryDisplay().id());
  EXPECT_EQ(ash::ShelfAlignment::kBottom, alignment);

  // Check the locked state, which is not exposed via prefs.
  EXPECT_FALSE(ash::ShelfTestApi().IsAlignmentBottomLocked());
}


text:
package org.jbox2d.testbed.tests;

import org.jbox2d.collision.Distance.SimplexCache;
import org.jbox2d.collision.DistanceInput;
import org.jbox2d.collision.DistanceOutput;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Color3f;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
import org.jbox2d.testbed.framework.TestbedSettings;
import org.jbox2d.testbed.framework.TestbedTest;

public class DistanceTest extends TestbedTest {

	Vec2 m_positionB;
	float m_angleB;

	Transform m_transformA;
	Transform m_transformB;
	PolygonShape m_polygonA;
	PolygonShape m_polygonB;

	@Override
	public String getTestName() {
		return "Distance";
	}

	@Override
	public void initTest(boolean argDeserialized) {

		input.transformA = new Transform();
		input.transformB = new Transform();
		{
			m_transformA = new Transform();
			m_transformA.setIdentity();
			m_transformA.position.set(0.0f, -0.2f);
			m_polygonA = new PolygonShape();
			m_polygonA.setAsBox(10.0f, 0.2f);
		}

		{
			m_positionB = new Vec2();
			m_positionB.set(12.017401f, 0.13678508f);
			m_angleB = -0.0109265f;

			m_transformB = new Transform();
			m_transformB.set(m_positionB, m_angleB);

			m_polygonB = new PolygonShape();
			m_polygonB.setAsBox(2.0f, 0.1f);
		}
		for (int i = 0; i < v.length; i++) {
			v[i] = new Vec2();
		}
	}

	DistanceInput input = new DistanceInput();
	SimplexCache cache = new SimplexCache();
	DistanceOutput output = new DistanceOutput();
	Color3f color = new Color3f(0.9f, 0.9f, 0.9f);
	Vec2[] v = new Vec2[Settings.maxPolygonVertices];
	Color3f c1 = new Color3f(1.0f, 0.0f, 0.0f);
	Color3f c2 = new Color3f(1.0f, 1.0f, 0.0f);

	@Override
	public void step(TestbedSettings settings) {
		super.step(settings);

		input.proxyA.set(m_polygonA);
		input.proxyB.set(m_polygonB);
		input.transformA.set(m_transformA);
		input.transformB.set(m_transformB);
		input.useRadii = true;
		cache.count = 0;
		getWorld().getPool().getDistance().distance(output, cache, input);

		addTextLine("distance = " + output.distance);
		addTextLine("iterations = " + output.iterations);

		{
			for (int i = 0; i < m_polygonA.m_vertexCount; ++i) {
				Transform.mulToOut(m_transformA, m_polygonA.m_vertices[i], v[i]);
			}
			getDebugDraw().drawPolygon(v, m_polygonA.m_vertexCount, color);

			for (int i = 0; i < m_polygonB.m_vertexCount; ++i) {
				Transform.mulToOut(m_transformB, m_polygonB.m_vertices[i], v[i]);
			}
			getDebugDraw().drawPolygon(v, m_polygonB.m_vertexCount, color);
		}

		Vec2 x1 = output.pointA;
		Vec2 x2 = output.pointB;

		getDebugDraw().drawPoint(x1, 4.0f, c1);

		getDebugDraw().drawPoint(x2, 4.0f, c2);
	}

	@Override
	public void keyPressed(char argKeyChar, int argKeyCode) {

		switch (argKeyChar) {
			case 'a' :
				m_positionB.x -= 0.1f;
				break;

			case 'd' :
				m_positionB.x += 0.1f;
				break;

			case 's' :
				m_positionB.y -= 0.1f;
				break;

			case 'w' :
				m_positionB.y += 0.1f;
				break;

			case 'q' :
				m_angleB += 0.1f * MathUtils.PI;
				break;

			case 'e' :
				m_angleB -= 0.1f * MathUtils.PI;
				break;
		}

		m_transformB.set(m_positionB, m_angleB);
	}
}